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.
Thanks!
CodePudding user response:
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);
});