Home > UI/UX Development > JavaScript > What is difference offset() and position()

What is difference offset() and position()

This post was most recently updated on August 5th, 2024

Hello everyone, in this post we will discuss about difference between offset() and position() with example.

offset()

  • The offset() method set or returns the offset coordinates (current position) for the selected elements, relative to the document.
  • offset() returns an object containing the properties top and left coordinate value.
  • When positioning a new element on top of an existing one, in particular for implementing drag-and-drop .offset() is more useful.

position()

  • The position() method set or returns the current position of an element relative to the offset parent.
  • position() returns an object containing the properties top and left coordinate value.
  • When positioning a new element near another and within the same container .position() is the more useful.

Consider following example which show offset and position coordinate values

<html>
<head>
<title>Diff between offset() and position()</title>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js” type=”text/javascript”></script>
<style>
#wrapper {
padding: 1em;
background: gray;
position: relative;
}

#test {
width: 5em;
height: 5em;
background: silver;
}
</style>

<script>
$(document).ready(function() {
$(‘#offset’).click(function() {
var test = $(‘#test’);
console.log(test.offset());
var top = test.offset().top;
var left = test.offset().left;
$(‘#output’).text(‘top: ‘ + top + ‘, left: ‘ + left);
});

$(‘#position’).click(function() {
var test = $(‘#test’);
console.log(test.position());
var top = test.position().top;
var left = test.position().left;
$(‘#output’).text(‘top: ‘ + top + ‘, left: ‘ + left);
});
});
</script> <!– load our javascript file –>

</head>
<body>
<p><button id=”offset”>offset()</button><button id=”position”>position()</button></p>

<div id=”wrapper”>
<div id=”test”></div>
</div>

<p id=”output”></p>

</body>
</html>

coordinates value using offset()
coordinates value using position()

This Article is TAGGED in . BOOKMARK THE permalink.

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 class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">