so, I'm having a game, and I want the user to reset the score when he clicks the button, and reset boundaries when he hovers over it. How can I do it so that he can both, hover and click
function reset_bounderies() {
let start = document.getElementById("start")
start.addEventListener("mouseover", function (event) {
game = true;
document.querySelectorAll(".boundary:not(.example)").forEach(item => {
item.classList.remove("youlose")
document.getElementById("status").innerHTML = `Begin by moving your mouse over the "S".`
})
})
start();
}
and the second function
function reset_game() {
let start = document.getElementById("start")
start.addEventListener("click", function (event) {
game = true;
score = 0;
print_score()
})
start();
}
P.S: I can't edit html or css file
CodePudding user response:
You can add two differents EventListener
to your button
function functionOne(){
console.log("functionOne")
}
function functionTwo(){
console.log("functionTwo")
}
const myButton = document.getElementById("myButton")
myButton.addEventListener('click', functionOne)
myButton.addEventListener('mouseover', functionTwo)
<button id="myButton">Click me !</button>
CodePudding user response:
You could also send both events to the same handler and use Event.type to execute specific code. This is useful when both events have some tasks in common.
['mouseover', 'click'].forEach(type => {
start.addEventListener(type, event => {
// common code
game = true;
if (event.type === "mouseover") {
console.log("MouseOver - Set Game Bounderies");
// code to reset bounds
}
else {
console.log("Click - Reset Game");
score = 0;
// other reset code
}
});
});
<button id="start">Start</button>