Brent
Brent

Reputation: 67

jQuery Image Map links change html in div

I am trying to display content based on the image map links. Example, click on a state, and show that state's html div content.

<img src="/territories.jpg" usemap="#Map" />

<map name="Map" id="Map">
  <area shape="poly" coords="5,49" href="#links" alt=""/>
  <area shape="poly" coords="4,137" href="#links" alt=""/>
  <area shape="poly" coords="-62,186" href="#links"/> alt=""/>
</map>

<div id="state1">State One Content</div>
<div id="state2">State Two Content</div>
<div id="state3">State Three Content</div>

A working example, but not an image map. http://jsfiddle.net/hKMFb/24/

A working image map, but this one only displays one state http://jsfiddle.net/leonardorb/4QaNx/5/

Upvotes: 0

Views: 1276

Answers (2)

Dfranc3373
Dfranc3373

Reputation: 2177

You can do this by matching the area item match the id of the state.

Heres a quick example code,

<map name="Map" id="Map">
  <area shape="poly" coords="5,49" href="#links" alt="" item="state1" />
  <area shape="poly" coords="4,137" href="#links" alt="" item="state2" />
  <area shape="poly" coords="-62,186" href="#links" alt="" item="state3" />
</map>

<div id="state1">State One Content</div>
<div id="state2">State Two Content</div>
<div id="state3">State Three Content</div>

//javascript
$("map#Map").click(function(ev){
        var target = $(ev.target);
        var item = target.attr('item');
          alert($("#" + item).html());

});

Here is a fixed version of your working example:

http://jsfiddle.net/4QaNx/128/

<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/94/U.S._Territorial_Acquisitions.png/320px-U.S._Territorial_Acquisitions.png" alt="" usemap="#texasmap" id="" />

<map id="usaMap" name="texasmap">
    <area shape="circle" coords="135,150,45" href="#" alt="" item="Rebuplic of Texas" id="texasArea"/>
    <area shape="circle" coords="250,180,35" href="#" alt="" item="Florida Area" id="floridaArea"/>
</map> 

<div id="message"></div>

$("#message").hide();

$("map#usaMap").click(function(ev){
    var target = $(ev.target);
    var targetId = target.attr('id');
    var item = target.attr('item');
      $("#" + targetId).show(); //By using "#" + targetId it chooses whatever ID is clicked on
      $("#message").html("You clicked the " + item).show(); //by changing the item value to what you want to display it will show it on click, and it replaces the html

});

Upvotes: 1

Dave
Dave

Reputation: 10924

Assuming your <div>s are names state1 through stateN where N == number of areas in map, and assuming the areas are listed in the same order as your state indexes: get the index of <area> that was clicked, then get the corresponding state <div> and show it:

$("#Map area").on("click", function(e) {
  e.preventDefault();
  var index = $("#Map area").index(this);
  $("#state" + index + 1).show();
});

I made a lot of assumptions--let me know if there are problems with those.

Upvotes: 0

Related Questions