CodesJava

Easy learning with example program codes

jQuery position()

The jQuery position () method is same as jQuery offset() in the sense that it is also used to retrieve the current position of an element. The only difference and the main difference between these two methods is:

The jQuery position() method is used to retrieve the current position of an element relative to the parent element, while the jQuery offset() method is used to retrieve the current position of an element relative to the document.

The jQuery position() method returns the value of top and left position in pixels. This method is especially useful to position a new element near another one.

Syntax:

$(selector).position() 

Example 1

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
<script>  
$(document).ready(function() {  
$("div").click(function () {  
var position = $(this).position();  
$("#lresult").html("left position: <span>" + position.left + "</span>.");  
$("#tresult").html("top position: <span>" + position.top + "</span>.");  
});  
});  
</script>  
<style>  
div { width:60px; height:60px; margin:5px; float:left; border-radius:120px}  
</style>  
</head>  
<body>  
<p>Click on any circle</p>  
<span id="lresult"> </span>  
<span id="tresult"> </span>  
<div  style="background-color:turquoise"></div>  
<div  style="background-color:cyan"></div>  
<div  style="background-color:blue"></div>  
<div  style="background-color:skyblue"></div>  
</body>  
</html>

Try it

JS Bin on jsbin.com

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status