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

window.addEventListener not working properly inside a conditional

Need some help with mousemove events within a conditional. I’ve created a variable to track the current state, and want it to trigger additional mousemove events only when active.

Currently, this is the code I have:

let awake = 0;
    window.addEventListener('click', function(e){
        if (awake === 0){
            //Do something
            awake = 1;
            console.log(awake);
        } else {
            window.addEventListener('mousemove', function(e){
                 //Do something else when awake === 1
        };
    });

Problem is, after the first click, a second additional click is required before the mousemove event will start to trigger. I’m not getting an errors in the console or anything so I’m not quite sure what’s the issue.

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

Thanks!

>Solution :

Don’t add the listener conditionally. Add it immediately, and check inside it whether awake is on or not.

let awake = 0;
window.addEventListener('mousemove', function(e) {
  if (awake) {
    console.log('movement while awake', Date.now());
  }
});
window.addEventListener('click', function(e) {
  awake = !awake;
  console.log('awake now', awake);
});
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