Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --
I don't like setting position using css()
, though often it's fine. I think the best bet is to use jQuery UI's position()
setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:
const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
left: baseOffset.left + leftOffset,
top: baseOffset.top + topOffset
});
This has the advantage of not arbitrarily setting $div
's parent to relative positioning (what if $div
's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div
doesn't have any offsetParent
, not sure if it would return document
, null
, or something else entirely.
offsetParent
has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.
$("#mydiv").css({top: '200px', left: '200px', position:'absolute'});
<-- good$("#mydiv").css({top: '200', left: '200', position:'absolute'});
<-- bad. Apparently, if position values are strings, you must include the units, or it'll have no effect. – Flunkey