I have one box (#fB) and one checkbox (#chck). I’m trying to put hover on this box based on checked or unchecked checkbox.
I’ve written condition IF, but this hover is triggered as FALSE too. I’ve tried put .pointerEvents = "none"; as a FALSE, but nothing happens.
Any advice where is the problem?
Thank you very much.
document.querySelector("#chck").addEventListener("click", changer);
var check = document.querySelector("#chck");
var box = document.querySelector("#fB");
function changer(){
if(check.checked){
box.addEventListener("mouseover", function(){
box.style.background = "green";
});
box.addEventListener("mouseout", function(){
box.style.background = "purple";
});
}else{
box.removeEventListener("mouseover", function(){
box.style.background = "green";
});
box.removeEventListener("mouseout", function(){
box.style.background = "purple";
});
}
};
>Solution :
It looks like your code is removing the event listeners from the box element when the checkbox is not checked. However, you are passing anonymous functions to the removeEventListener method, which won’t work because those functions are not the same as the functions that were added as event listeners.
To fix this, you can store references to the event listener functions in variables, and then pass those variables to the removeEventListener method. Here is an example of how you might do this:
document.querySelector("#chck").addEventListener("click", changer);
var check = document.querySelector("#chck");
var box = document.querySelector("#fB");
// Event listener functions
var mouseOver = function() {
box.style.background = "green";
};
var mouseOut = function() {
box.style.background = "purple";
};
function changer() {
if (check.checked) {
// Add the event listeners
box.addEventListener("mouseover", mouseOver);
box.addEventListener("mouseout", mouseOut);
} else {
// Remove the event listeners
box.removeEventListener("mouseover", mouseOver);
box.removeEventListener("mouseout", mouseOut);
}
}