Absolute placing with jQuery

I needed to do some absolute positioning to an element with jQuery, based on it’s original size… Well here’s how to do it !

The issue I had

I have an element that is placed in the flow in css (position: static) and I needed, with jQuery to place it absolutely, at the exact same place.

parents with position: relative and others eventualities, this turned out to be a massive pain, until I found a really simple solution

The 3 lines solution

$(function() {
    var offset = $("#my-element").offset();
    $("#my-element").css("position", "absolute");

The .offset() method returns the absolute position in the view port. It doesn’t take parent position value into account. So first of all we store this in an offset variable.

We then set the position of our element to absolute.

Then we use the .offset() method again, passing the previously created variable as an argument. jQuery Will take care of the rest and place the element exactly where it was before, but absolutely.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>