jQuery offset()
method is the used to get the current offset of the first matched element.
Below the syntax of offset()
.
Return the offset co-ordinates:
$(selector).offset();
Set the offset co-ordinates:
$(selector).offset({top:value,left:value});
Set offset co-ordinates using a function:
$(selector).offset(function(index, currentoffset))
# Example1 - Set the value of input field
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery offset()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
var offset = $("p").offset();
alert("Top: " + offset.top + " Left: " + offset.left);
});
});
</script>
</head>
<body>
<p style="margin:10px 0 0 10px"><lorem ipsum dolor sit</p>
<button style="margin:0 0 10px 0;background:#e8e8e8;" class="btn" id="button">Click here to return offset coordinate of p element</button><br />
</body>
</html>