jQuery Tutorial Tutorials - jQuery .offset() method

jQuery .offset() method

The .offset() method in jQuery is used to get/set the coordinates of the selected element,relative to the document.

jQuery .offset() method Syntax

.offset()
.offset(coordinates)
.offset(function)
Parameter Type Description
coordinates PlainObject An object containing the properties top and left(relative to document) to set
funtion(index, oldCoordinates) Function a function returning the the coordinates to set.
index is the position of the element in the set.(based on 0)
oldCoordinates is the old coordinates relative to document.

.offset()

Get the current coordinates of the first matched element relative to the document.

example

Get the offset of the first paragraph

var offset = $("p").offset();
$('#Top').text('Top:' + offset.top);
$('#left').text('Left:' + offset.left);
console.log(offset);

Try now

.offset(coordinates)

Set the coordinates of every matched elements

example

Set the offset of each paragraph with same coordinates relative to the document

$("p").offset({top:100,left:50});

Try now

.offset(function)

Set the offset of each paragraph with different coordinates

$("p").offset(function(index,oldValue){
    var top = 30*index + 100;
    var left = 20*index + 50;
    return {top:top,left:left};
});

Try now

Date:2019-08-20 15:58:25 From:www.Lautturi.com author:Lautturi