Reputation: 69
I got one begginer issue. I've got "menu", the menu is styled table and got code in jQuery that makes the menu moves. My question is, why I can't use $this varible in my code? I'm big begginer in jQuery so be patient with me. I will be happy for any answer.
$(document).ready(function(){
$('.item').hover(function(){
$($this).stop().animate({paddingLeft: '20px'}, "slow");
}, function(){
$($this).stop().animate({paddingLeft: '0px'}, "slow");
});
});
My code: jsFiddle
Upvotes: 0
Views: 588
Reputation: 9480
$this
and this
are not same. In development when we write as var $this = $(this)
than It become's a jQuery object. $this
denote that in this
currently we have a jQuery object.It is only for a refrence you can use any other variable for that $this is not necessary.you can write vat $that = $(this)
and use that It will behave same.
Upvotes: 0
Reputation: 58531
often people use $this
to cache $(this)
so that they don't have to repeatedly initiate the jQuery object, which is expensive.
$this = $(this)
$this.stop()
$this.animate()
// etc...
This is done by convention, and the $
character in javascript has no special meaning. Thought I would mention, as nobody else seems to have mentioned the reason.
Upvotes: 2
Reputation: 1527
use this
$(document).ready(function(){
$('.item').hover(function(){
$(this).stop().animate({paddingLeft: '20px'}, "slow");
}, function(){
$(this).stop().animate({paddingLeft: '0px'}, "slow");
});
});
Upvotes: 0
Reputation: 33983
The $
prefix (in Javascript/jQuery code) before a variable is typically a convention used to indicate that the variable is a jQuery object (as opposed to a plain Javascript one). If you've seen it before, it's just like any regular variable.
You should use $(this)
instead, which 'wraps' this
in a jQuery object.
Upvotes: 2