How can I set the offset()
function to do what margin-top: 100px;
would do?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function() {
$(document).scrollTop( $("#position_page").offset().top );
});
</script>
<div id="aboutUs">
About us content...
</div><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="position_page">
Header content...
</div>
jQuery offset() MethodThe offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.
The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.
Difference between offset() and position() Method:The jQuery UI offset() is relative to the document. The jQuery UI position() is relative to the parent element. When you want to position a new element on top of another one which is already existing, its better to use the jQuery offset() method.
You can just add on the offset to the end of the scrollTop like this:
$(document).scrollTop( $("#position_page").offset().top + 100);
Here is a working example: http://jsfiddle.net/mtruty/rks3H/
simply add 100 to the scroll position
<script type="text/javascript">
$(function() {
$(document).scrollTop( $("#position_page").offset().top + 100);
});
</script>
<div id="aboutUs">
About us content...
</div><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="position_page">
Header content...
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With