offset()
method is used to set or returns the offset coordinates for the selected elements, relative to the document.offset()
methods are following :Parameter | Description | {top:value,left:value} | It is a mandatory parameter while setting the offset. It specifies the top and left co-ordinates in pixels. |
---|---|
function(index,currentoffset) | It is an optional parameter. It specifies a function that returns an object containing the top and left coordinates.
|
<!DOCTYPE html>
<html>
<head>
<title>jQuery offset() Method</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
var x = $("h1").offset();
alert("Top: " + x.top + " Left: " + x.left);
});
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
</style>
</head>
<body>
<h1><a href="http://www.freetimelearning.com" target="_blank">www.freetimelearning.com</a></h1>
<button type="button" class="btn">Click Here! (offset())</button>
</body>
</html>
offsetParent()
method returns the first positioned parent element. An element can be positioned with jQuery, or with the CSS position property (relative, absolute, or fixed).<!DOCTYPE html>
<html>
<head>
<title>jQuery offsetParent() Method</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").offsetParent().css("background-color", "#0099da");
});
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
.box{border:1px solid #F00; width:98%; position:absolute; left:10px; top:50px;}
.box_2{border: 1px solid #0099da; margin:50px; background-color:#F60;}
</style>
</head>
<body>
<button type="button" class="btn">Set background-color</button>
<div class="box">
<div class="box_2">
<p style="padding:10px; color:#FFF;">
<strong>Dummy Text :</strong> Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
</div>
</div>
</body>
</html>