38 of 119 menu

The offset method

The offset method allows you to get the position of an element relative to the document, unlike the position method, which gets coordinates relative to the parent's indents. The offset method is more useful when positioning a new element on top of an existing one for global manipulations, such as implementing drag-and-drop. As a result, the method returns an object containing the top and left properties. Calculation errors may occur if the user changes the page size. The method also does not get coordinates of hidden elements.

Syntax

Get current coordinates. In some cases, the obtained values ​​may be fractional:

$(selector).offset();

To change the coordinates of an element, you need to pass an object containing the top and left properties:

$(selector).offset({top: 40, left: 40});

We can also apply the given function to each element in the set. In this case, the function will receive the element number in the set as its first parameter, and the object with coordinates top and left as its second parameter. this inside the function will point to the current element. The element coordinate values ​​will change to those returned by the function:

$(selector).width(function(number in set, {current coordinates}));

Example

Let's get the position of the div (green square) using the offset method, and then, referring to the keys of the resulting object, output this information:

<div id="result">click a square ...</div> <div id="test"></div> #test { position: absolute; top: 40px; left: 40px; width: 100px; height: 100px; background: green; color: white; margin-top: 10px; cursor: pointer; } $('*', document.body).click(function(event) { let offset = $(this).offset(); event.stopPropagation(); $('#result').text('Left: ' + offset.left + ', Top: ' + offset.top); });

Example

Let's change the coordinates of the second paragraph:

<p style="margin-left: 10px;">text1</p> <p style="margin-left: 10px;">text2</p> $('p').last().offset({top: 40, left: 60});

See also

  • method position,
    which allows you to get the current coordinates of an element
  • method offsetParent,
    which allows you to get the closest positioned ancestor of an element
  • method css,
    which allows you to get and change the CSS styles of an element
azbydeenesfrkakkptruuz