learning_dev
learning_dev

Reputation: 145

Execute conditional code onload()

I have two buttons on my page

<button id="reset" type="reset" value="Reset" 
onClick="window.location.reload()"/>
&nbsp;
<button id="random" type="button" onclick="randomPeg();">Empty random 
peg</button>

function randomPeg()
{
window.location = window.location.href + "#refresh";
window.location.reload();
}
//At the start of JS code below
document.addEventListener("DOMContentLoaded", function(event) { 
if(window.location.hash == "#refresh"){
    window.location.hash="";
    //Some more code
});

The first button just reloads the window. On clicking the second button 'Empty random peg', I want to reload the page and then execute some more code after. I tried a few things with putting hash in the url but it doesn't seem to be working.

Upvotes: 0

Views: 627

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

You could set a value into the persistent localStorage, and check at pageload if this value exists:

function reload(){
  localStorage.setItem("showfancystuff",true);
  window.location.reload();
}

//test on load
window.addEventListener("load",function(){
  if(localStorage.getItem("showfancystuff")){
    localStorage.removeItem("showfancystuff");
    alert("wohoo weve reloaded!");
  }
});

Upvotes: 2

Related Questions