Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this) inside $('#something').css({...})

Tags:

jquery

this

I tried to apply css with jquery to a div element, but it wont accept the $(this) parameter. I wonder why cant I use $(this) as a referer to the div element.

blabla.css({
'top': $(window).width()/2-$(this).width()/2+'px', 
'left': $(window).width()/2-$(this).width()/2+'px'  
});

ERROR: Uncaught TypeError: Object # has no method 'width'

Thanks in advance..

ps: I know I can use here a direct id call inside the $(), but I expected this will work.

like image 249
zsitro Avatar asked Nov 15 '25 15:11

zsitro


2 Answers

Note that you are not running a callback, you're passing an object to .css. So, this doesn't not refer to blabla - the element - but to the current context defined when the function that contains this code was called (and that could vary). This context doesn't have .width, and then you get an error.

You will have to explicitly reference the width, as in blabla.width()

like image 59
Marcelo Diniz Avatar answered Nov 18 '25 19:11

Marcelo Diniz


if $(this) is blabla, why not use blabla.width() instead $(this).width()?

like image 45
Pablo Martinez Avatar answered Nov 18 '25 21:11

Pablo Martinez