Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript changes to the dom lost when back button pressed

I have this view that changes the text inside a div.

The user can then click on a link to jump to another page. But when the user presses the "back" button all DOM changes are lost.

FF remembers the changed div text but Chrome and IE do not.

I've found similar question, but in my case it is not possible to summarize the state by a url hash because the div contains random data.

I need is so that when the user goes back, the div is filled from the identical series of numbers.

<script type="text/javascript">
    function ChangeText() {
        var newText = "";

        for (var i = 0; i < 10; i++) {
            newText = newText + Math.random() * 100;
            newText = newText + "<br />";
        }

        $("#container").html(newText);
    }
</script>

<div id="container">
    INITIAL TEXT
</div>
<button onclick="ChangeText()">Click here to generate random numbers</button>
<br/>
<a href="http://www.google.com">External link</a>
like image 255
Riccardo Bassilichi Avatar asked May 22 '12 12:05

Riccardo Bassilichi


People also ask

What event is fired when the back button of a browser is pressed?

The popstate event is fired each time when the current history entry changes (user navigates to a new state). That happens when user clicks on browser's Back/Forward buttons or when history. back() , history.

What happens when the DOM changes?

When you update the DOM, the reflow and repaint happen. Every time the DOM changes, the browser needs to recalculate the CSS, do a layout and repaint the web page. React doesn't really do anything new. It's just a strategic move.

Which button is available only after using the back button?

When you hit the back button in your browser, or(alt+left) in chrome, the browser actually just loads the cached HTML file in the history.


1 Answers

You can store your html in LocalStorage, so when user go back, you fill the content with your localStorage:

<script type="text/javascript">
    function onLoadPage(){
        if(window.localStorage.getItem("newText") != null){
            $("#container").html(window.localStorage.getItem("newText"));
        }
    }

    function ChangeText() {
        var newText = "";

        for (var i = 0; i < 10; i++) {
            newText = newText + Math.random() * 100;
            newText = newText + "<br />";
        }

        window.localStorage.setItem("newText") = newText;

        $("#container").html(newText);
    }
</script>

<div id="container">
    INITIAL TEXT
</div>
<button onclick="ChangeText()">Click here to generate random numbers</button>
<br/>
<a href="http://www.google.com">External link</a>
like image 163
Lucas Anschau Avatar answered Oct 19 '22 09:10

Lucas Anschau