0

I can't figure this out, sounds like it should be simple but I tried all kinds of variations of what I found here javascript - How to use window.scroll to automatically scroll on pageload? - Stack Overflow but trying to modify it to scroll horizontally instead... and couldn't get any of them to work. If I used code to scroll to the bottom, that worked fine.

I'm trying to run the code within

$(function () {
    function Scrolldown() {
        // alert("hi")
       //$("img").scrollIntoView(false);
    //    window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
        // window.scrollTo(-5000, 0);
//        $("img").scrollIntoView(false);
   }
   
   window.onload = Scrolldown; 
});

My page simply consists of a bunch of images, all the same width.. which are wider than the view area (or whatever the technical term is) of the browser... i.e. you need to scroll right to see the rest of the image.

I would like on load for the user to see the right end of the image, the left part can be off-screen. As opposed to the default where the left is visible and the right is offscreen.

I'm not averse to animation, but without is preferable. But the important thing is just finding something that works.

ycomp
  • 8,316
  • 19
  • 57
  • 95

1 Answers1

2

This seems to do the trick for me:

window.addEventListener('load', (event) => {
  setTimeout(() => {
    window.scrollTo({
      left: window.innerWidth,
      behavior: 'smooth',
    });
  }, 0);
});

So I guess you can adapt it to fit your code like so:

$(function () {
  function Scrollright() {
    setTimeout(() => {
      window.scrollTo({
        left: window.innerWidth,
        behavior: 'smooth',
      });
    }, 0);
  }
   
   window.onload = Scrollright; 
});
Leonardum
  • 444
  • 4
  • 8
  • thanks, unfortunately it doesn't work for me.. I'm sure it is good code.. so I thought a bit more and I think maybe the problem is now that the because the images on my automatically refresh, and the image sizes are not known until the happens, I'm guessing when the onLoad occurs it has no idea how wide the page with the images will be. I guess I should try to find an event that loads after an image completes and run the scrollTo from in there – ycomp Jun 07 '22 at 07:11
  • I have made an adjustment to the answer that sets a timeout. Since this will cause the function to be executed in a separate thread, it might fix the problem. Of course you can add milliseconds as needed, but it is impossible to know how fast any client will load the images on the page. If image quality is not too important, you can also use some online tool to reduce the file size of the images. This should speed up the loading. – Leonardum Jun 07 '22 at 14:32