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
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
Share Improve this question asked Apr 20, 2013 at 20:53 albru123albru123 692 silver badges11 bronze badges 4- 1 This was not the question... – Flo Schild Commented Apr 20, 2013 at 20:55
- Hum, what's this answer ? I'm just saying that the asker is not asking for something about PHP, but for something about jQuery, and has a doubt about $this ! – Flo Schild Commented Apr 20, 2013 at 21:02
-
He was making a joke because in PHP variables are declared like
$this
. There, not it's been spelled out for you. – Willem Ellis Commented Apr 20, 2013 at 21:53 - I'm learning both jQuery and PHP, sometimes it's too much for me. :-D – albru123 Commented Apr 21, 2013 at 9:41
5 Answers
Reset to default 11It's just supposed to be $(this)
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.
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.
use this
$(document).ready(function(){
$('.item').hover(function(){
$(this).stop().animate({paddingLeft: '20px'}, "slow");
}, function(){
$(this).stop().animate({paddingLeft: '0px'}, "slow");
});
});
$this
and this
are not same. In development when we write as var $this = $(this)
than It bee'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.