Saturday, March 21, 2015

Image Changer using Javascript

To change the images using javascript. Please follow step by step process.
For this atleast you need a lil bit knowledge of javascript.

1.) Readout the selector where we want to change image
var myImage = document.querySelector('img');
 here img is the Html tag

2.) Get the attribute
var mySrc = myImage.getAttribute('src');

3.) Now set the data in the attribute or we can say Image Name
myImage.setAttribute('src', 'img/chrome.png');

Now why we are using mySrc variable?
Because this will take the name of the image and then by using if-else condition we can differentiate and can save the different name.

Now this whole part will be shown when we CLICK on the image.
So
myImage.onclick = function(){
   var mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/chrome.png') {
      myImage.setAttribute ('src','images/firefox.png');
    } else {
      myImage.setAttribute ('src','images/chrome.png');
    }
}