skip to Main Content

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


  1. Use window.scrollTo instead of specifically scrolling the body. The main scrolling element (document.scrollingElement) may be either the <body> or <html> element.

    window.scrollTo(0, 1110);
    

    In standards mode (with <!doctype html>), the scrolling element is the <html> element, so scrolling document.body has no effect. In quirks mode, it is typically the <body> element, so your code works in that case.

    Login or Signup to reply.
  2. As per the MDN explanation of the defer attribute, you cannot use defer for inline scripts, which you’re doing:

    Warning: This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

    The defer attribute has no effect on module scripts — they defer by default.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search