Reputation: 379
I'm trying to create a sidebar navigation menu where when you hover over the elements, it makes a certain div appear.
The HTML looks like:
<ul id="nav">
<li id="item1">Item1</li>
<li id="item2">Item2</li>
<li id="item3">Item3</li>
</ul>
<div id="item1_content">
blah1
</div>
<div id="item2_content">
blah2
</div>
<div id="item3_content">
blah3
</div>
The jQuery looks like:
$(document).ready(function() {
//hides all content at load
$("#item1_content").hide();
$("#item2_content").hide();
$("#item3_content").hide();
//when item 1 hovered over, hide all else and display item 1 content
$("#item1").hover(function(){
$("#item2_content").hide(),
$("#item3_content").hide(),
$("#item1_content").fadeIn("fast");
});
$("#item2").hover(function(){
$("#item3_content").hide(),
$("#item1_content").hide(),
$("#item2_content").fadeIn("fast");
});
$("#item3").hover(function(){
$("#item2_content").hide(),
$("#item1_content").hide(),
$("#item3_content").fadeIn("fast");
});
However, while this works if you hover over the elements slowly, it seems to not hide all text when you go over them quickly. I'm a complete beginner with jQuery, and I'm sure this is the least efficient way to go about doing this. How can I get a nice hover effect that won't bug up, and how can I make my code more efficient? (Using classes, in particular)
Thank you.
Upvotes: 0
Views: 433
Reputation: 129782
I haven't been able to find that it doesn't fade in, but since the fade is fast, it is perhaps just me not finding it. What I have found is that the elements somtetimes doesn't disappear. This is because they're hidden while they're still in the process of fading in. To solve that you need to call stop(true, true)
to stop any ongoing animation and jump to its end before you hide.
I made some modifications to your DOM, to use classes for identification, rather than ID.
<ul id="nav">
<li id="item1">Item1</li>
<li id="item2">Item2</li>
<li id="item3">Item3</li>
</ul>
<div class="item1 content">
blah1
</div>
<div class="item2 content">
blah2
</div>
<div class="item3 content">
blah3
</div>
One thing I would change would be to add a style .content { display: none; }
, rather than calling $('.content').hide();
on DOMReady, as this might casue the items to flicker during page load.
Now that they're classes, we can reduce this to one method:
$(function() {
$("#nav li").mouseover(function(){
$(".content").stop(true, true).hide(),
$("." + $(this).attr('id')).fadeIn("fast");
});
});
I changed hover
to mouseover
, since hover triggers twice (once on mouseover, and once on mouseout) which seems not to be what you want.
The second selector in the mouseover callback is looking for whatever item has the same class as the current item's ID. So hover over #item3
will look for .item3
.
Upvotes: 1