Toggle div's on hover

Mariola picture Mariola · Mar 6, 2014 · Viewed 20.7k times · Source

I have a test UL list that goes like this:

<ul>
<li id="firstdiv">First div</li>
<li id="seconddiv">Second div</li>
<li id="thirddiv">Third div</li>
....
</ul>

And, bellow that i have related div's, aka:

<div id="firstdiv">Content Here</div>
<div id="seconddiv">Content Here</div>
<div id="thirddiv">Content Here</div>

I was wondering how could i make each div only shows when its LI item is hovered, maybe with some fadein effect. I tried with some other answers from here, but no luck :\

Answer

George picture George · Mar 6, 2014

As I've mentioned, it is important that your ids are unique. So you need to find another way to reference your <div>s. May I suggest using data-* attributes:

HTML

<ul>
    <li data-id="firstdiv">First div</li>
    <li data-id="seconddiv">Second div</li>
    <li data-id="thirddiv">Third div</li>
</ul>

Then your jQuery could look something like the following:

$('ul li').on({
    'mouseenter':function(){
        $('#'+$(this).data('id')).fadeIn();
    },'mouseleave':function(){
        $('#'+$(this).data('id')).fadeOut();
    }
});

JSFiddle