On one page of the site it is necessary that when you refresh the page, the user shows that part of the page where he was. Those. if he scrolled down and updated the page, he automatically stayed down. I assume that this is done using localStorage , but I still do not understand exactly how. The information on the Internet could not find, strange.

The page is not just text, but also div , img .. is it not enough important ..

    2 answers 2

     let cords = ['scrollX','scrollY']; // ΠŸΠ΅Ρ€Π΅Π΄ Π·Π°ΠΊΡ€Ρ‹Ρ‚ΠΈΠ΅ΠΌ записываСм Π² локалсторадТ window.scrollX ΠΈ window.scrollY ΠΊΠ°ΠΊ scrollX ΠΈ scrollY window.addEventListener('unload', e => cords.forEach(cord => localStorage[cord] = window[cord])); // ΠŸΡ€ΠΎΠΊΡ€ΡƒΡ‡ΠΈΠ²Π°Π΅ΠΌ страницу ΠΊ scrollX ΠΈ scrollY ΠΈΠ· localStorage (Π»ΠΈΠ±ΠΎ 0,0 Ссли Ρ‚Π°ΠΌ Π΅Ρ‰Π΅ Π½ΠΈΡ‡Π΅Π³ΠΎ Π½Π΅Ρ‚) window.scroll(...cords.map(cord => localStorage[cord])); 
    • Would you at least explain that the code does =) And there are a lot of ES6 that everyone does not know how to work with - alexoander
    • Although the decision is good - alexoander
    • @alexoander added comments. Already ES8 on the nose - Darth
    • Do not forget about legacy and generally there is no need to chase ahead of the tail. Thank! - alexoander

     $(window).scroll(function(){ var s= $(this).scrollTop(); console.log(s ); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div>12</div> <div>12</div><div>12</div><div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> <div>12</div> 

    You can use scrollTop() to store the scroll position. This value can be saved in localStorage , and then fed to the same function to go to this value on the page. But one thing - for such a transition it is necessary that the entire DOM has already been built and drawn otherwise there will be errors.

    • And if the scrolling is horizontal? - Darth
    • @Darth By analogy with scrollLeft (); - alexoander