Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrolltop within a div is not working in jquery

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/

like image 467
akash Avatar asked Dec 15 '14 06:12

akash


1 Answers

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():

.position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

.offset()

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.

like image 65
Roko C. Buljan Avatar answered Sep 27 '22 23:09

Roko C. Buljan