I need to scroll vertically the image using javascript, it works:
<html>
<head>
<title>Document</title>
<script defer>
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
document.querySelector('body').scrollTo(0,1110)
}
});
</script>
</head>
<body>
<div>
<img src="https://www.cam.ac.uk/sites/www.cam.ac.uk/files/shorthand/204072/Y4qHbMIuob/assets/tW5uZTUHvH/credit-timothy-soar_160804-forest-133_1440-by-2560-750x1333.jpeg" />
</div>
</div>
</body>
</html>
But if my page has at the beginning the tag <!DOCTYPE html>
it stops working.
Tested using Chrome, Edge and Firefox.
Why? How to solve it?
2
Answers
Use
window.scrollTo
instead of specifically scrolling the body. The main scrolling element (document.scrollingElement
) may be either the<body>
or<html>
element.In standards mode (with
<!doctype html>
), the scrolling element is the<html>
element, so scrollingdocument.body
has no effect. In quirks mode, it is typically the<body>
element, so your code works in that case.As per the MDN explanation of the
defer
attribute, you cannot usedefer
for inline scripts, which you’re doing:So, put your script in its own js file, and then load that with
<script src="yourfile.js" defer></script>
, and now it’ll actually load deferred, as intended.