Image Changer
With the review of JavaScript basics completed, let's add some new features to our Procedures site.
Empowering Today’s Learners to Become Tomorrow’s Leaders
With the review of JavaScript basics completed, let's add some new features to our Procedures site.
In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image.
Position the cursor over the image below.
Right-click the mouse and a shortcut menu appears.
Click Save image as... to display the Save As dialog box. (Procedures folder)
Save this image in your images folder.
Rename the image Moon.png.
6. Add the JavaScript below to your main.js file. (Also delete your Hello world! JavaScript from the earlier exercise.)
// Image switcher code
let myImage = document.querySelector('img');
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'images/Earth.png') {
myImage.setAttribute('src','images/Moon.png');
} else {
myImage.setAttribute('src','images/Earth.png');
}
}
5. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one.
This is what happened. You stored a reference to your <img> element in the myImage variable. Next, you made this variable's onclick event handler property equal to a function with no name (an "anonymous" function). So every time this element is clicked:
The code retrieves the value of the image's src attribute.
The code uses a conditional to check if the src value is equal to the path of the original image:
If it is, the code changes the src value to the path of the second image, forcing the other image to be loaded inside the <img> element.
If it isn't (meaning it must already have changed), the src value swaps back to the original image path, to the original state.