COMisHARD
COMisHARD

Reputation: 923

Javascript function onclick, back button to "refresh" page

I have looked around, but I'm not seeing anything that specifically addresses this. My goal is to have a link, which can be clicked to either add content or "undo" the act of adding that content. I am trying to us the following:

function ShowDiv() {
  if (null == window.set) {
    document.getElementById("box2").innerHTML = "Some Content";
    window.set = "set";
  } else
    location.reload();
}
<a href="#" onclick="ShowDiv();">Link</a>
<div id="box2"></div>

This allows me to click the link to show some content inside some div. And then to click the link again to remove that content.

However, I am wondering if there is a way to achieve this result, that also allows the user to click the browser's back button to return the page to the state it was in before triggering the function (e.g., to reload the page).

Upvotes: 0

Views: 610

Answers (1)

dsh
dsh

Reputation: 12234

You are looking for the HTML5 history API. This allows you to push state onto the history as if the browser loaded a different location without actually sending a request and replacing all content and javascript state. This allows the back and forward buttons to work, as long as your JavaScript code shows the correct content according to the current URL.

Resources:

Upvotes: 2

Related Questions