Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript hover via addEventListener

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading