# Specifying that one set of HTML elements controls a corresponding set

How could the following code be made more concise?

HTML structure

<body>
<ul id="main-nav">
<li></li>
<li></li>
<li></li>
</ul>
<section>
<div class="toggle">
<div class="secondState"></div>
</div>
</section>
<section>
<div class="toggle">
<div class="secondState"></div>
</div>
</section>
<section>
<div class="toggle">
<div class="secondState"></div>
</div>
</section>
</body>


jQuery

$('#main-nav li:eq(0)').on({ mouseenter: function () {$('body section:eq(0)').find('.secondState').stop().fadeIn(600);
},
mouseleave: function () {
if ($('body section:eq(0) .toggle').hasClass('current')) { return false; } else {$('body section:eq(0)').find('.secondState').stop().fadeOut(600);
}
}
});
$('#main-nav li:eq(1)').on({ mouseenter: function () {$('body section:eq(1)').find('.secondState').stop().fadeIn(600);
},
mouseleave: function () {
if ($('body section:eq(1) .toggle').hasClass('current')) { return false; } else {$('body section:eq(1)').find('.secondState').stop().fadeOut(600);
}
}
});
$('#main-nav li:eq(2)').on({ mouseenter: function () {$('body section:eq(2)').find('.secondState').stop().fadeIn(600);
},
mouseleave: function () {
if ($('body section:eq(2) .toggle').hasClass('current')) { return false; } else {$('body section:eq(2)').find('.secondState').stop().fadeOut(600);
}
}
});


The only part of the code that changes are the index values. What if you don't specific the index yourself, but use the indexof() to let it determ the index itself:

var index;
$('#main-nav li').on({ mouseenter: function () { //alert($(this).index());
index = $(this).index();$('body section:eq(' + index +')').find('.secondState').stop().fadeIn(600);
},
mouseleave: function () {
if ($('body section:eq(' + index +') .toggle').hasClass('current')) { return false; } else {$('body section:eq(' + index +')').find('.secondState').stop().fadeOut(600);
}
}
});


I place the index into a variabe so the code doesnt have to determ the index over and over. Now i only fill the index when the mouseenters, because you will have the index of the element were you entered with.

jsFiddle

I hope this helps.

• well it is not so simple, i added html structure to my question, as you see \$(this) cannot reefer to ('#main-nav') i think that index num is the key to optimize this code, and of course your code is not working – gidzior Oct 9 '13 at 12:44
• @gidzior wat? #main-nav is not quite the same as #main-nav li – John Dvorak Oct 9 '13 at 12:54
• @Jan Dvorak well it is obvious, it was my shorthand, sorry for that, nevertheless nkmol example is wrong – gidzior Oct 9 '13 at 12:58
• I do apologize. I did not fully acknowledge the code. Check my update! – nkmol Oct 9 '13 at 13:15
• this is exactly what i meant, thx a lot for your help and sorry for not completely question – gidzior Oct 9 '13 at 13:26