December 7, 2010

Correct HTML scrolling element of main viewport (+jQuery)

Question by tillda

When I want to scroll a website by javascript code what is the corrent element to set the .scrollTop property on?

Is it window, document, document.body or html element?

Does jQuery have some trick to detect the intention to scroll the main viewport and unify the calls? It seems to me that sometimes $(window).scroolTop(value) works, but sometimes it doesn’t.

Answer by bobince

Normally, the <html> element, aka document.documentElement. However if you are using Quirks Mode, <body> (document.body) represents the viewport instead. (HTML/CSS doesn’t explicitly state/require this, but it is how all modern browsers work.)

You don’t ever want to be in Quirks Mode, but if you’re writing a script for inclusion on other people’s pages you will have to deal with it:

var viewport= document.compatMode==='BackCompat'? document.body : document.documentElement;
// do something with viewport.scrollTop

jQuery uses window.scrollTo() instead of setting the scroll properties directly. Either way is pretty much the same in practice. You could argue that using scrollTo is a bit cleaner in that it avoids relying on the viewport being represented by a particular element, but then jQuery still has to use scrollTop/scrollLeft to read the current value of the ‘other’ property anyway, so no big win. You can use pageXOffset/pageYOffset to read the current scroll position without relying on a particular element, but it’s not supported everywhere so you still have to fallback to the scrollTop method.

Sadly none of these properties/methods have been standardised in the past. CSSOM Views finally address this.

Answer by Starx

Depends on what you are scrolling, document/Window or a division

...

Please fill the form - I will response as fast as I can!