×

jQuery Tutorial

jQuery Examples

jQuery Practice

How to position one element relative to another with jQuery?

In this tutorial, we'll see how to position one HTML element relative to another using jQuery?
Submitted by Pratishtha Saxena, on July 24, 2022

Basically, if we want to get the position of any HTML element, we can use either position() method or offset() method of jQuery. Both these methods return the position, i.e., the left and top distances from the leftmost corner of the window in pixels. But the difference is that the position() works relative to its parent tag whereas the offset() always works relative to the document/screen/window.

But here, the method that can help to set the position of the element relative to another is offset().

jQuery offset() Method

As discussed above, the offset() method gets the top and left values relative to the window and not according to its parent element. This method is also used to set the position of the specified HTML element.

Syntax:

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

So, the first way represents how to get the position of the selector whereas the second method tells how to set the position of the selector by passing the left and top values to it.

Let's see an example of this.

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      #box{
      border: 1px;
      background-color: yellow;
      }
    </style>
  </head>
  <body>
    <h1>jQuery</h1>
    <div id="box">
      <h2>Test Box</h2>
      <p>This is an example for implementing the methods.</p>
    </div>
    <br>
    <button id="offsetBtn">Offset</button>
  </body>
</html>

jQuery:

$(document).ready(function(){
	$('#offsetBtn').click(function(){
		$('#box').offset({top:0, left:0});
	});
});

Output:

Here, since the highlighted div has been set to the position as top: 0 and left: 0, therefore on clicking the button, the div is relocated to the top and leftmost position of the window, covering up the heading.

Example 1: position one element relative to another

Example 2: position one element relative to another





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.