Swapping the position of two images with JavaScript -


so trying make if click on button switch images placement. doesnt switch placement instead changes src of each image id. works when click button once, after images no longer switch. code

function swapimages(){     var image1 = document.getelementbyid("image1")     var image2 = document.getelementbyid("image2")     if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {         image1.src = '/jmurphy9/111/images/earth.jpg';     } else {         image1.src = '/jmurphy9/111/images/earthrise.jpg'; }     if (image2.src = '/jmurphy9/111/images/earth.jpg') {         image2.src = '/jmurphy9/111/images/earthrise.jpg'; }     else {         image2.src = '/jmurphy9/111/images/earth.jpg'; } }  function init(){     var button1 = document.getelementbyid("btn1")     button1.onclick = swapimages; }  window.onload = init; 

the problem src property have absolute path image, not relative 1 checking

one possible solution use .indexof() given below

function swapimages() {     var image1 = document.getelementbyid("image1")     var image2 = document.getelementbyid("image2")     if (image1.src.indexof('/jmurphy9/111/images/earthrise.jpg')>-1) {         image1.src = '/jmurphy9/111/images/earth.jpg';     } else {         image1.src = '/jmurphy9/111/images/earthrise.jpg';     }     if (image2.src.indexof( '/jmurphy9/111/images/earth.jpg')>-1) {         image2.src = '/jmurphy9/111/images/earthrise.jpg';     } else {         image2.src = '/jmurphy9/111/images/earth.jpg';     } } 

or can use .getattribute()

if (image1.getattribute('src') == '/jmurphy9/111/images/earthrise.jpg') { } 

but since want swap, can do

function swapimages() {     var image1 = document.getelementbyid("image1")     var image2 = document.getelementbyid("image2")     var src = image1.src;     image1.src = image2.src;     image2.src = src; } 

demo: fiddle


note: in if condition using assignment(=) operator instead of comparison operator(==), image1.src = '/jmurphy9/111/images/earthrise.jpg' in if should image1.src == '/jmurphy9/111/images/earthrise.jpg'