⊗jqDmPo 69 of 113 menu

Positioning in jQuery

To work with element coordinates, jQuery has the methods position and offset.

These methods are used to get or change the current coordinates of an element and return an object containing the top and left properties as a result.

Calculation errors may occur if the user changes the page size. Also, the methods do not receive the coordinates of hidden elements.

The offset method gets the position of an element relative to the document, and position gets the position of an element relative to the parent's offsets.

Let's say we have the following HTML code:

<div id="parent"> <p id="test">text</p> </div> <p id="text1"></p> <p id="text2"></p>

The paragraphs are linked to CSS styles:

#parent { width: 150px; border: 1px solid blueviolet; } #test { margin: 5px; text-align: center; outline: 1px solid green; }

Let's get the position of the div test using these methods, and referring to the keys of the obtained object, we will output this information below in paragraphs:

let offset = $('#test').offset(); $('#text1').text( '(OFFSET()) left: ' + offset.left + ', top: ' + offset.top ); let position = $('#test').position(); $('#text2').text( '(POSITION()) left: ' + position.left + ', top: ' + position.top );
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline