Q:

How to get the position of an element relative to the parent using jQuery

0

How to get the position of an element relative to the parent using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery position() method

You can easily find the position of an element relative to the offset parent using the jQuery position() method. It is only applicable for the visible elements. That means, you can get the position of elements with visibility: hidden; but not with display: none;.

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Find Element's Position Relative to the Parent</title>
<style>
     #box{
        width:150px;
        height:100px;
        background: orange;
    }
    .container{
        margin: 20px;
        padding: 30px;
        border: 2px solid #666;
        position: relative;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            var position = $("#box").position();
            alert("Current position of the box is: (left: " + position.left + ", top: " + position.top + ")");
        });
    });
</script>
</head>
<body>
    <div class="container">
        <button type="button">Get Box Position</button>
        <p><strong>Note:</strong> Play with the value of container's padding property or insert more content inside container to see how the jQuery position() method works.</p>
        <div id="box"></div>
    </div>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to find mouse position relative to the documen... >>
<< How to get the position of an element relative to ...