NotRocketScientist NotRocketScientist - 1 month ago 8
HTML Question

I click an input radio and change an image src, by clicking again...how do I change the image back how it was?

I have this code:

https://jsfiddle.net/Suiberu/rxu8wgxf/

//INPUT RADIO ON & OFF
var prv;
var markIt = function(e) {
if (prv === this && this.checked) {
this.checked = false;
prv = null;
} else {
prv = this;
}
};

$(function() {
$('input.limit_radio').on('click', markIt);
});


//CHANGE IMAGE
function changeImage(imgName) {
image = document.getElementById('theimage');
image.src = imgName;
}


Clicking on an input type radio.. and yes it has to be an input type radio,
I do manage to change an img src.
Thanks to some jquery code I can manage to turn off the input radio. But the changed image remains as it was changed in the first place.
So when I turn off the input type radio I would like to get back the original img src.
How do I achieve this?

Sorry, but javascript or jquery are not my strongest skills, but you can verify what am I asking for just checking the url above.

Thanks!

Answer

I removed the onclick handler and added a data attribute to swap out the urls.

https://jsfiddle.net/jjwilly16/37yn9xzy/1/.

<img src="http://www.cbc.ca/i/img/theme/default/plus-up.png" name="theimage" id="theimage" data-alternate="https://www.ucl.ac.uk/2034/images/icons/arrow-blue-left.png"/>


/INPUT RADIO ON & OFF 
var prv;
var markIt = function(e) {
    if (prv === this && this.checked) {
    this.checked = false;
    prv = null;
  } else {
    prv = this;
  }
    var img = document.getElementById('theimage'),
        alternate = img.getAttribute('data-alternate'),
      src = img.src;
  img.src = alternate;
  img.setAttribute('data-alternate', src);

};

$(function() {
  $('input.limit_radio').on('click', markIt);
});