Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Google Chrome and iOS remember scroll position in div after returning back?

The problem is that the scroll container is a div, not body. And that causes Google Chrome and iOS to fail to remember scroll position of the div after users go to another page and then return back.

The related CSS code is as follows. The scroll container is #container.

* {
    margin: 0;
    padding: 0;
    }

html {
    height: 100%;
    }

body {
    height: 100%;
    overflow: hidden;
    }

#container {
    height: 100%;
    overflow: auto;
    }

And here is a demo on jsFiddle. Please reproduce the issue on Google Chrome and iOS by scrolling the content to about 50% (or any other noticeable length), click on a hyperlink to go to nother page, and then click browser's Back button.

Is there a uncomplicated way to make Google Chrome and iOS remember scroll position like Firefox does?


== EDIT in response to an answer ==

A simple .html file to test if any code in onbeforeunload works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script>
        window.onbeforeunload = function () {
            alert('Are you sure');
        }
    </script>
</head>
<body>
    <div id="container">
        <p><strong><a href="http://stackoverflow.com/">Go to Stack Overflow</a></strong>. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas laoreet imperdiet diam, in sodales velit porta eget.</p>
    </div>
</body>
</html>
like image 539
Ian Y. Avatar asked Sep 27 '22 15:09

Ian Y.


1 Answers

Demo Url and Session Based https://jsfiddle.net/w2wkcx0e/6/

Demo Url Based https://jsfiddle.net/w2wkcx0e/3/

Demo https://jsfiddle.net/w2wkcx0e/1/

you could save the position at leaving page and reload it upon page reloading.

Let me know if doesn't work in all browsers you want it to work.

if (localStorage.scrollPos != undefined)
    $('#container').scrollTop(localStorage.scrollPos);

window.onbeforeunload = function () {
    localStorage.setItem("scrollPos", $('#container').scrollTop());
};
like image 153
Muhammad Umer Avatar answered Oct 18 '22 08:10

Muhammad Umer