Search code examples
javascriptjqueryhtmlimageimagemap

Swapping an image via jquery when using an image map


I am trying to build a image map link that swaps the image out for another image. The idea is that the user can click on a small defined area (that would say "click here") and the image will swap to a second image. The second image will have a small area that says "previous" so clicking the same area will make the image return to the original one.

This is as far as I got, so far no image changes, however it seems like the image map is working.

Can anyone figure out how to get this working correctly?

html:

<div id="picture_here">
    <img src="https://www.google.com.au/images/srpr/logo11w.png" id="picture"  usemap="#imageMap"/>
</div>

<map name="imageMap">
    <area shape="rect" coords="0,0,100,100"  href="JavaScript: test(); void(0);">
</map>

Javascript:

var swapImage = 1;


function test(){
        if (swapImage == 1){
            swapImage = 2;
            $('#picture').attr('src', 'https://s1.yimg.com/rz/d/yahoo_frontpage_en-AU_s_f_p_bestfit_frontpage_2x.png');
        }else if (swapImage == 2){
            swapImage = 1;
            $('#picture').attr('src', 'https://www.google.com.au/images/srpr/logo11w.png');
        }
}

See JSFIDDLE


Solution

  • Actually it works. In jsfiddle, you are getting js error because test function not found in js fiddle. If you put js code in script tag in html section like below, you can see it is working.

    <div id="picture_here">
        <img src="https://www.google.com.au/images/srpr/logo11w.png" id="picture"  usemap="#imageMap"/>
    </div>
    
    <map name="imageMap">
        <area shape="rect" coords="0,0,100,100"  href="JavaScript: test(); void(0);">
    </map>
        <script>
        var swapImage = 1;
    
    
    function test(){
            if (swapImage == 1){
                swapImage = 2;
                $('#picture').attr('src', 'https://s1.yimg.com/rz/d/yahoo_frontpage_en-AU_s_f_p_bestfit_frontpage_2x.png');
            }else if (swapImage == 2){
                swapImage = 1;
                $('#picture').attr('src', 'https://www.google.com.au/images/srpr/logo11w.png');
            }
    }    
        </script>
    

    Demo

    Alternativelly, you can use "No wrap - in " config in jsfiddle. You can see demo for that

    Demo No Wrap