How to change second image back to first image when clicked again


The first image shows a map of the USA and the second image shows a map of the USA with Indiana’s population. When you click specifically on Indiana on the first image, it shows the second image, which contains the population.
It works up until I have to click on the second image, so it can go back to the first image, which doesn’t have Indiana’s population. I want the second image to go back to the first image when I click on it.

Javascript:


    var currentMap = 1;
    
    function swapMap() {
    
    if(currentMap==1) {
        document.getElementById("us_map1").src = "usmap2.jpg";
        currentMap = 2;
    } else {
        document.getElementById("us_map1").src = "usmap1.jpg";
        currentMap = 1;
    }
    }
    
    document.getElementById("pop").addEventListener("click", swapMap); 

HTML:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    
        <img src="img/usmap1.jpg" width="600" height="500" id="us_map1" alt="" usemap="#wmap"/>
        <map name="wmap">
          <area shape="poly" coords="399,154,425,147,433,190,418,207,397,210" id="pop">
    </map>
    <script src="L9.js"></script>
    </body>
    </html>

Source: JavaSript – Stack Overflow

November 20, 2021
Category : News
Tags: addeventlistener | html | image | javascript | onclick

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.