$ (this) inside $ ('# something'). css ({...})
I tried to apply css with jquery to a div element, but it won't accept the $ (this) parameter. I wonder why I can't use $ (this) as the div element referent.
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 a direct call id here internally $()
, but I expected this
to work.
source to share
Note that you are not doing a callback, you are passing an object .css
. Thus, it this
does not refer to blabla
- an element - but to the current context defined when calling the function that contains that code (and this may change). This context does not have .width
, and then you will get an error.
You will need to explicitly refer to the width as in blabla.width()
source to share
I needed a solution too. I wanted to use jQuery to center the floating divs. I created this function called onload and to fit the window:
$("div[class~='floatCenter']").each(function () {
var elementWidth = $(this).outerWidth() / 2;
var parentWidth = $(this).parent().outerWidth() / 2;
var marginPixels = parentWidth - elementWidth;
$(this).css("margin-left", marginPixels + "px");
});
I ended up taking a different route, focusing my div with CSS, but the concept of usage $(this)
remains the same.
source to share