Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scrollTop() not working on 'body' element in Firefox

Tags:

I do not understand why the scrollTop() jquery function is not working on the 'body' element on Firefox.

$('body').scrollTop(0);

I fixed my issue using:

$(window).scrollTop(0);

However according to the jquery documentation scrollTop() is supposed to work on all elements like in this example:

$( "div.demo" ).scrollTop( 300 );

I have also tested with 'nav' and 'main' but it is not working either.

like image 278
j3r6me Avatar asked Feb 04 '14 15:02

j3r6me


People also ask

Why is scrollTop not working?

If your CSS html element has the following overflow markup, scrollTop will not function. To allow scrollTop to scroll, modify your markup remove overflow markup from the html element and append to a body element.

Is scrollTop deprecated?

scrollTop is deprecated for Chrome in Strict Mode. That's why developers fall back on the logical OR operator. document.

What is $( window scrollTop ()?

jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.

What is Document body scrollTop?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


2 Answers

Scroll

$(window).scrollTop(0); seems to be supported by all browsers IE9+ (maybe IE8 but I don't test on that any more).

Animated Scroll

If you want to animate a scroll, jQuery returns an error if using the window object (1.11.2 tested). Instead, to animate a scroll, it's best to use both html and body to cover engines which utilise either one. So:

$('html, body').animate({scrollTop:0},500); will scroll to the top of the browser in half a second.

Scroll Position

You cannot use $('html,body').scrollTop() to find the current scroll position of the page - at least Chrome doesn't support this (always returns 0). Instead, to consistently find the scroll position of a page, it's necessary to use $(window).scrollTop();.

like image 154
dewd Avatar answered Nov 04 '22 22:11

dewd


Use window if you want consistency between browsers.

$(window).scrollTop();
like image 39
Ivan V. Avatar answered Nov 05 '22 00:11

Ivan V.