0

Below is my code , I want the game function to be called only when user/client clicks on "Refresh" icon or presses "F5",i.e. Function "game" should be called after page refreshes.Below is my code

window.onload = game;

function game() {
  var p1 = Math.floor(Math.random() * 6) + 1;
  var p2 = Math.floor(Math.random() * 6) + 1;
  var imgp1 = "images/dice" + p1 + ".png";
  var imgp2 = "images/dice" + p2 + ".png";
  document.querySelector(".img1").setAttribute("src", imgp1);
  document.querySelector(".img2").setAttribute("src", imgp2);
  if (p1 > p2) {
    document.querySelector("h1").textContent = "Player 1 wins !";
  } else if (p1 === p2) {
    document.querySelector("h1").textContent = "It's a Draw !";
  } else {
    document.querySelector("h1").textContent = "Player 2 wins !";
  }
}

I tried the above method but function gets called whenever page is loaded even for first time , Also I tried this method from the answer How do I call/execute a function when user clicks on refresh or presses F5 button using plain Javascript only?

window.onload = function () {
  var reloading = sessionStorage.getItem("reloading");
  if (reloading) {
    sessionStorage.removeItem("reloading");
    game();
  }
};

function reloadP() {
  sessionStorage.setItem("reloading", "true");
  document.location.reload();
}

But here even the function is not being called even one time, Hope you get my question !

Raxy
  • 335
  • 1
  • 3
  • 9
  • Do you want to call the function before the page refreshes or after? – Heretic Monkey Aug 05 '20 at 14:48
  • I want to call function after page refreshes ! – Raxy Aug 05 '20 at 14:53
  • It appears you took that code from [this answer](https://stackoverflow.com/a/41905026/215552). You are required to give attribution to authors of code on Stack Overflow. Please do so. And feel free to stop using exclamation points everywhere. – Heretic Monkey Aug 05 '20 at 14:59
  • Sorry, my Bad, I am quite new here and will follow certain ethics here onwards. But can you help me out , the linked answer is not helping me to solve my issue – Raxy Aug 05 '20 at 15:06
  • Did you implement that code completely? There is a link to a jsFiddle demo where the `reloadP` function is applied to a button. You might need to instead copy the first line like `window.onbeforeunload = function () { sessionStorage.setItem("reloading", "true"); };` so that the session storage item is set before the page is unloaded. – Heretic Monkey Aug 05 '20 at 15:10

0 Answers0