why are use the position method in the JQuery and also explain with example.

0 votes
57 views
Ethan Karla asked 28-Jul-2021 in Web Application by Ethan Karla

why are use the position method in the JQuery and also explain with example.

1 Answer

1 votes
Ravi Vishwakarma answered 29-Jul-2021 by Ravi Vishwakarma

The jQuery position() method is used to find the current position of the selected element. Position has two values called top and left. so that it tells the current position of the element. i.e. shows the left position and the top position.

Syntax
$(selector).position()

<!DOCTYPE html>

<html>
<head>
    <title>The jQuery Example</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
    <script type='text/javascript' language='javascript'>
        $(document).ready(function () {
            var h = 60;
            $('div').each(function (index) {
                $(this).css('height', h);
                h = h + 60;
            });
            $('div').click(function () {
                var position = $(this).position();
                $('#result').html('top position: ' + position.top + ' left position: ' + position.left );
            });
        });
    </script>
    <style>
        div {
            width: 50px;
            margin: 5px;
            float: left;
        }
    </style>
</head>
<body >
    <p>Click on any shape:</p>
    <span id='result'></span><br /><br />
    <div style='background-color: #ab1402'></div>
    <div style='background-color: #10abcd'></div>
    <div style='background-color: #27ffe5'></div>
    <div style='background-color: #ee1205'></div>
</body>
</html>

Output:

why are use the position method in the JQuery and also explain with example.