Search code examples
jqueryimagemap

jquery image map - How can I change background sprite image position?


I am using an image map on a page that i want to tie into an un ordered list and change the position of the sprite background image based on what hot spot they click on ( i hope i explained that properly):

<map name="image-map">
<area id="hometownnorth" title="HometownNorth" shape="poly" coords="71,140,71,124" href="#" alt="HometownNorth">
</map>

<div>
    <ul>
        <li><a href="#" class="HomeTownNorth">&nbsp;</a></li>
    </ul>
</div>

a.hometownnorth { height:50px; width:325px; background: url(/resources/images/logo.jpg) 0px -6px no-repeat;}

So for this example, when the user clicks on the area #hometownnorth, it will change the background position to -324px -6px


Solution

  • You can attache the click event to the area inside your image-map. Here is a working example:

    (I set the clickable area ONLY to the top-left 50X50 rectangle)

    $('#hometownnorth').click(function(e) {
      e.preventDefault();
      $('#image1').css('backgroundPosition', '-50px -50px');
    });
    img#image1 {
      background: url(http://www.w3schools.com/images/colorpicker.png) no-repeat top left;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <img id="image1" src="#" width="150" height="150" alt="Planets" usemap="#map1" />
    
    <map name="map1">
      <area id="hometownnorth" title="HometownNorth" shape="rect" coords="0,0,50,50" href="#asd" alt="HometownNorth" />
    </map>