×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery position() Method

jQuery | position() Method: Learn about the jQuery position() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

position() Method

Sometimes it is necessary to know about the positions of the elements placed on the page. So that we can plan the design of the further document according to it. The position() method helps to do the same. This method returns the position of the selected element with respect to the parent element. It returns only the top and the left distances from its parent element top and left respectively in pixels.

position() Method Syntax

$('selector').position();

It takes no parameters. It used two attributes – top & left in order to access the top and left positions of the element respectively. The position() method returns the offset of the first element matched and sets the offset of all the elements matched.

This method is a little different from the offset() method of jQuery as the offset() method sets or returns the offset of the element with respect to the document, whereas the position() method helps us to get the position of the element with respect to its parent element. Below given example below showcases the implementation of the position() method in jQuery.

jQuery position() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery - Position</h2>
    <p>Click the button to get the Position of the selected element.</p>
    <button>Position</button>
    <hr>
    <img style="height: 150px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <hr>
    <h3 id="one" style="color:crimson ;"></h3>
    <h3 id="two" style="color:crimson ;"></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            var property = $('img').position();
            $('#one').html('Top: ' + property.top);
            $('#two').html('Left: ' + property.left);
        })
    });
  </script>
</html>

Output:

Example 1: jQuery position() Method


Comments and Discussions!

Load comments ↻





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