I'm having issues setting scrollTop cross browser. I did a search which said to use the solution below.
I've currently got:
var body = document.documentElement || document.body;
body.scrollTop = 200;
this works in IE, not chrome
if I switch it round:
var body = document.body || document.documentElement;
body.scrollTop = 200;
it works in chrome, not IE
how to fix this?
There are some interoperability issues and incompatibilities in this area. In order to avoid user agent sniffing (and to ease migration to the standard API, where document.documentElement.scrollTop controls the viewport, rather than document.body.scrollTop), a new API was implemented in modern browsers.
Basically, have a function for scrolling that does this -
function scrollViewport(top, left)
{
var eViewport = document.scrollingElement
if (eViewport)
{
if (typeof top !== "undefined")
{
eViewport.scrollTop = top;
}
if (typeof left !== "undefined")
{
eViewport.scrollLeft = left;
}
}
else
{
// Do your current checks or set the scrollLeft and scrollTop
// properties of both of documentElement and body, or user agent
// sniffing, if you must.
// Example -
// var scrollTop = 200;
// Chrome, Internet Explorer and Firefox, I think.
// document.documentElement.scrollTop = scrollTop;
// Safari, at least up to version 11, I think.
// document.body.scrollTop = scrollTop;
// Or just (I am not sure I recommend this)...
// window.scrollTo(0, scrollTop);
}
}
Read the Opera article for more information.
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