Reputation: 13207
$('#element').children('ul').children('li').children('a').hover(function(){
var _this = $(this);
_this.siblings('div').show();
},function(){
_this.siblings('div').hide();
})
It works like it should, showing the div. but it will not hide it after. i guess _this isnt defined in the callbacl function. how do i pass it inside that function without having to select it again from the DOM? I think its a pretty basic javascript question, i just can´t figure it out.
Upvotes: 1
Views: 588
Reputation: 322462
You need this in both functions:
var _this = $(this);
But a little nicer way to do it is like this:
$('#element > ul > li > a').hover(function(e){
$(this).siblings('div').toggle( e.type === 'mouseenter' );
});
...or if you were hoping to avoid multiple calls to .siblings()
, you could do this:
$('#element > ul > li > a').each(function() {
var $th = $(this);
var sibs = $th.siblings('div');
$th.hover(function(e){
sibs.toggle( e.type === 'mouseenter' );
});
});
FYI: When you do $(this)
, you're not selecting anything from the DOM. this
is simply a direct reference to the element that is set for you when the handler is called.
Upvotes: 3
Reputation: 35890
In your example you pass two functions as arguments to the .hover() method, so any variables you declare inside the functions, are only available within the scope of that function. So if you need to use the _this
variable in the second function, you need to declare it again.
But in your case, the intermediate variable should not be necessary, and you can omit it altogether:
$('#element').children('ul').children('li').children('a').hover(function(){
$(this).siblings('div').show();
} ,function(){
$(this).siblings('div').hide();
})
Upvotes: 3
Reputation: 530
If all of your links inside #element
are inside li
, you can call them using $('#element > a').hover()
.
Try this:
$('#element > a').mouseover(function () { $(this).siblings('div').show(); }).mouseout(function () { $(this).siblings('div').hide(); });
Upvotes: 0
Reputation: 2196
Why don't you use mouseenter and mouseleave?
Or maybe:
$('#element').children('ul').children('li').children('a').hover(function(){
var _this = $(this);
_this.siblings('div').show();
},function(){
var _this = $(this);
_this.siblings('div').hide();
})
The _this is "private" if i'm not mistaking in the first function statement...
Upvotes: 0