Reputation: 19425
My goal is to:
I'm able to fade out 'foo' on mouse over, but I'm not able to fade in 'bar' and then return to normal state when I move the mouse outside the 'bar' div.
I have the following code:
html
<ul>
<li>
<div class="foo"></div>
<div class="bar"></div>
</li>
<li>
<div class="foo"></div>
<div class="bar"></div>
</li>
</ul>
css
li .bar { display: none; }
js
// On mouse over, fade out 'foo' and fade in 'bar'
jQuery('.foo').mouseover(function() {
jQuery(this).fadeOut(function() {
jQuery('.bar').fadeIn(); <-- This is wrong. I need to get the bar inside this li
});
// On mouse out, fade out 'bar' and fade in 'foo'
jQuery('.bar').blur(function() {
jQuery(this).fadeOut(function() {
jQuery('.foo').fadeIn();
});
Here is my bad jsFiddle attempt: http://jsfiddle.net/TvCT5/2/
Appreciate a push in the right direction :)
Upvotes: 0
Views: 568
Reputation: 707328
The general design pattern is as follows. Instead of this:
jQuery('.bar').fadeIn();
use this to find the .bar
object with a common <li>
parent with the object that triggered the event:
jQuery(this).closest("li").find('.bar').fadeIn();
or because your two items are siblings, you can more simply use this:
jQuery(this).siblings('.bar').fadeIn();
This finds the nearest ancestor that is an <li>
tag and then finds the .bar
object in that ancestor which will be the one that matches up with the trigger of the event.
The full code would look like this:
// On mouse over, fade out 'foo' and fade in 'bar'
jQuery('.foo').mouseover(function() {
jQuery(this).fadeOut(function() {
jQuery(this).siblings('.bar').fadeIn();
});
// On mouse out, fade out 'bar' and fade in 'foo'
jQuery('.bar').blur(function() {
jQuery(this).fadeOut(function() {
jQuery(this).siblings('.foo').fadeIn();
});
It's a bit unusual to pair .mouseover()
with .blur()
since those aren't matched pairs, but using .mouseover()
and .mouseout()
may also have issues because you're hiding the object that triggers the .mouseover()
.
Upvotes: 1
Reputation: 207901
Is this the effect you're looking for?
jQuery:
jQuery('.foo').mouseover(function(){
jQuery(this).fadeOut(function(){jQuery(this).siblings().fadeIn();});
});
jQuery('.bar').mouseout(function(){
jQuery(this).fadeOut(function(){jQuery(this).siblings().fadeIn();});
});
Upvotes: 1