Search code examples
jqueryhtmlimagemap

Use image maps to show and hide div elements


This is my code so far..

DEMO

I'm wanting the user to be shown the blue text only if they click the blue circle etc...

I guess I just have to change the attributes of the div elements but I'm not very comfortable with jQuery and unsure of the most elegant way to do this.

HTML

<img src="http://www.j-creative.biz/wp-content/uploads/2015/10/primary-colours-300x171.png" usemap="#test1" alt="" />
<map id="primarytest" name="test1">
  <area shape="circle" coords="50,75,50" href="#" item="red"/>
  <area shape="circle" coords="150,75,50" href="#" item="blue"/>
  <area shape="circle" coords="250,75,50" href="#" item="yellow"/> 
</map>

<div class="one" style="display:none" id="redtext">
<h5>
HelloRed
</h5>
</div>
<div class="one" style="display:none" id="bluetext">
<h5>
HelloBlue
</h5>
</div>
<div style="display:none" id="yellowtext">
<h5>
HelloYellow
</h5>
</div>

jQuery

$('[item="red"]).click(function() {
$(".one").hide();
    $("#redtext").show();
    return false;
});

Solution

  • Your current code is just missing a closing quote on the selector and jQuery from the fiddle. Fix those issues and it works:

    Updated fiddle

    That being said, you can improve the logic by following DRY principles. To do this you can put a common class on the area elements as well as a data attribute to specify which element they should show when clicked on. You can then use a single event handler on all of them. Try this:

    <img src="http://www.j-creative.biz/wp-content/uploads/2015/10/primary-colours-300x171.png" usemap="#test1" alt="" />
    <map id="primarytest" name="test1">
        <area shape="circle" coords="50,75,50" href="#" class="circle" data-target="redtext" />
        <area shape="circle" coords="150,75,50" href="#" class="circle" data-target="bluetext" />
        <area shape="circle" coords="250,75,50" href="#" class="circle" data-target="yellowtext" />
    </map>
    
    <div class="one" id="redtext">
        <h5>HelloRed</h5>
    </div>
    <div class="one" id="bluetext">
        <h5>HelloBlue</h5>
    </div>
    <div class="one" id="yellowtext">
        <h5>HelloYellow</h5>
    </div>
    
    $('.circle').click(function(e) {
        e.preventDefault();
        $(".one").hide().filter('#' + $(this).data('target')).show();
    });
    

    Example fiddle