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 !