When you set an element's offset with jQuery.offset({coords})
it also sets the CSS property position
to absolute
.
I have a div, however, that I set to position: fixed
in my CSS, and I want it to remain that way, even after setting the offset of the element with jQuery.
Now, I'm sure I can probably set the offset, then set position: fixed
again, but I was wondering if there is a way I can tell jQuery to set the position to fixed instead of absolute when it sets offset.
HTML
<div class="searchResults">
...
</div>
CSS
DIV.searchResults {
position: fixed;
padding: 20px;
background-color: red;
z-index: 501;
}
jQuery
$("DIV.searchResults").offset({left: 0, top: 0});
Rendered HTML
<div class="searchResults" style="position: absolute; top: 0px; left: 0px;">
...
</div>
Obviously, since jQuery is setting the position in the style, it will trump the value of my CSS class. So I need a way to tell jQuery to set position
to fixed
instead of absolute
, or tell it to set the offset without setting the value of the CSS property position
.
Contrast this with .position (), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset () is more useful. .offset () returns an object containing the properties top and left.
JQuery Offset() Method. The offset() method helps in returning relative position for the selected elements in pixels. It has two types of object properties which represents top and left positions in pixels.
Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for margins set on the <html> document element. While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.
The .offset () setter method allows us to reposition an element. The element's border-box position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.
As I commented above, in your case all you need is to modify the CSS for top and left like this:
$("DIV.searchResults").css({left: 0, top: 0});
Because the $.offset setter method only manipulates the left, top and position values to make the element relative to the page (from static to relative, and from fixed to absolute). Since you want it position fixed, set the values directly.
Maybe not that elegant, but I think you can just chain .css()
after that to be sure that position
is set to fixed
like this:
jquery
$("DIV.searchResults").offset({
left: 0,
top: 0
}).css("position" : "fixed");
Not tested, but I think that'll work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With