I have a javascript file that I want to run everytime a button is clicked in my HTML, at the moment this is refreshing the page but want it to run the javascript file below;
HTML
<h1>Refresh Me</h1>
<div><button onclick="window.location.reload()" type="button" class="button">Let's Find Out</button></div>
javascript
var randomNumber1 = Math.floor(Math.random()*6)+1;
var randomDiceImage = "dice"+randomNumber1+".png";
var randomImageSource = "images/"+randomDiceImage;
var image1 = document.querySelectorAll('img')[0].setAttribute("src",randomImageSource);
var randomNumber2 = Math.floor(Math.random()*6)+1;
var randomDiceImage2 = "dice"+randomNumber2+".png";
var randomImageSource2 = "images/"+randomDiceImage2;
var image2 = document.querySelectorAll("img")[1].setAttribute("src",randomImageSource2);
if(randomNumber1 > randomNumber2){
document.querySelector("h1").innerText = "Kirsty Makes Tea";
}
else if(randomNumber1 < randomNumber2){
document.querySelector("h1").innerText= "Danny Makes Tea";
}else{
document.querySelector("h1").innerText= "Its a draw";
}
Tried On Click and element listener but possibly incorrectly
2
Answers
use a click event listener on the whole window :
You could do this by adding all the javascript into a single function.
javascript
And then use this function in your html: