Reputation: 2157
I want to animate scrolltop
with in a div when I animate body scroll it is working fine for me
But when I am using it with in a div
it's fails.
This is working fine for me http://jsfiddle.net/yazaLyxs/
$('body').animate({
scrollTop: $('#myId').offset().top
}, 'slow');
Then why this code is not working ?
$('.myClass').animate({
scrollTop: $('#myId').offset().top
}, 'slow');
http://jsfiddle.net/qVWuv/198/
Upvotes: 7
Views: 19308
Reputation: 206102
OK since no-one answered exactly about what's all about:
.position().top
does not take into account an element's margin. jsFiddle demo
Your first example might work in Chrome, but not in Firefox, cause of the slight differences in documentElement
.
To account for it you'll have to use:
$('html, body').animate({
Now, let's look the difference between Methods .position()
and .offset()
:
Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
if the above is clear, and you want to get the inner child
element position inside a positioned parent*, you'll need to use .position()
.
#parent {
height: 300px;
background: teal;
margin: 500px 0 0 0;
overflow:scroll;
position:relative; /* NEEDED! */
}
Now, you might have set the inner's element margin to 500px
but it's top position is still 0
px!
console.log( $('#child').position().top ); // 0
therefore you need to set a top:
style (instead of margin
) and position:
to the #save
element in order to use $('#child').position().top
: http://jsfiddle.net/RokoCB/qVWuv/203/ (or at least put some other elements before it or some content).
*If you don't set a "position:" CSS property to the parent element you need to subtract the parent's top position or offset.
Upvotes: 5
Reputation: 24001
if in html
<div class="myClass">
<label></label>
<label id="myId">target Label</label>
</div>
and in css
div{
height: 100px;
width: 100px;
overflow: auto;
}
in js
$('.myClass').animate({
scrollTop: $('#myId').position().top
}, 'slow');
everything should work .. Jsfiddle
Upvotes: 2
Reputation: 26312
$('body').animate({
scrollTop: $('#myId').position().top
}, 'slow');
This working fine becauase you set div at margin-top:500px; that make vertical scroll into picture over body.
So you need a DOM element having enough height to get a vertical scroll, please note this element is parent element not the target element i.e. tag which contains your div.
Check this Jsfiddle Demo
Upvotes: 0