Search code examples
jquerymouseentermouseleavesimplify

Mouseenter / Mouseleave Simplifying jQuery


I am building a website for a company promotion and there are 24 map shape "hot spots" on the page that open 24 separate divs. Not my design, but I'm not high enough up to argue my case, so I am going with it. The code that was written by a co-worker is hideous (at least I think so) ---

$(".hover1").mouseenter(function(){
    $(".winner1").fadeIn();
}).mouseleave(function(){
    $(".winner1").stop().fadeOut();
});

(x24)

For all 24 different "hot spots" and divs. So you can imagine that each one change to ".hover2", ".hover3", etc... And the same with ".winner2", ".winner3", etc...

This code is around 120 lines.

My question, as I am not a jQuery expert by a long shot, is how to simplify this? I know there has to be a way, I just do not know it.

Each div and hot spot are labeled as such -- "hover1" / "winner1" , "hover2" / "winner2" , etc -- and are connected that way.

Any help would be greatly appreciated, thanks in advanced!!

:-)

EDIT

Here is the HTML

For the map

<map name="Map">
    <area shape="rect" coords="6,1,258,232" class="hover1"/>
</map> 

So when you hover over that, this shows up

<div class="winner1 badge male">
    <div class="winnerText">
        <p><span>Winner:</span> Clay Cauley</p>
        <p><span>Date:</span> December 3<sup>rd</sup>, 2012</p>
        <p><span>Prize:</span> XBOX 360</p>
    </div>
</div>

Solution

  • Assuming you can amend the HTML, try this:

    <map name="Map">
        <area shape="rect" coords="6,1,258,232" class="hover" data-target="winner1" />
        <area shape="rect" coords="2,2,2,2" class="hover" data-target="winner2" />
        <area shape="rect" coords="3,3,3,3" class="hover" data-target="winner3" />
        <area shape="rect" coords="4,4,4,4" class="hover" data-target="winner4" />
        <area shape="rect" coords="5,5,5,5" class="hover" data-target="winner5" />
    </map> 
    
    $(".hover").hover(function() {
        $("." + $(this).data("target")).fadeIn();
    },
    function() {
        $("." + $(this).data("target")).stop().fadeOut();
    });