Muad Muad -4 years ago 38
HTML Question

Listen to a mouse event on condition

I want to "listen to" a mouse event only if a checkbox is clicked. Therefore I have the following code:

HTML

<input type="checkbox" id="magicLens" onchange="magicLens()">
<label for="magicLens">Magic Lens</label>


JS

function magicLens(){
const magicLens_checked = document.getElementById('magicLens').checked;

if (magicLens_checked === true){
canvas.addEventListener('mousemove', e => {
myAnonymous = arguments.callee;
...
// draw something at the current mouse position
// and therefore use the 'e' event object
});
}
else {
canvas.removeEventListener('mousemove', myAnonymous);
}
}


Problem is, that the drawing (a lens) also occurs when the checkbox is not checked (
false
). I'm not even sure if
removeEventListener()
is the right way to deal with it (though I already tried the whole thing without it and result was the same).

Maybe you have a better idea to describe the issue in the title. Feel free to edit!

Answer Source

It's easier to actually always listen to the event and in there check whether the checkbox is checked.

const canvas = document.getElementById('canvas');

canvas.addEventListener('mousemove', e => {
    const magicLens_checked = document.getElementById('magicLens').checked;

    if (!magicLens_checked) {
        return;
    }

    // Do something with e
    console.log(e);
});

You can check it out in this Fiddle. (I added the event listener to document, to avoid creating an arbitrary canvas, but it works the same way)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download