Question

when the user clicks 'on' an EventListener gets added:

document.addEventListener('mousemove', getCursorXY, false);

when the user clicks 'off' the EventListener is not removed and when the user clicks 'on' again the same EventListener gets added again:

document.addEventListener('mousemove', getCursorXY, false);

Is this problematic? Are there two Listeners running then, or is the first just overwritten with the second?

Was it helpful?

Solution

The advantage of using addEventListener over properties like onclick is that you can attach as many event handlers as you'd like to on the element.

This also means that adding another event handler does not automatically remove the previously set event handlers, as that would defeat the purpose, you have to remove those manually with removeEventListener.

document.removeEventListener('mousemove', getCursorXY, false);

OTHER TIPS

Yes, you will have multiple event listeners firing for that event. Even if the code somehow manages to work correctly, it's inefficient, and something you should take care to avoid.

The mousemove event is fired by the browser very often, and it's really important to code any event handlers efficiently for this event, and to make sure you don't end up with a ton of listeners for it. Sometimes you need multiple listeners, and by all means do it if you need it, but you don't need it from what I'm seeing.

I recommend you just keep track of the fact that you already added the listener, and use that fact to avoid adding the listener twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top