How to check whether dynamically attached event listener exists or not?
I did something like that:
const element = document.getElementById('div');
if (element.getAttribute('listener') !== 'true') {
element.addEventListener('click', function (e) {
const elementClicked = e.target;
elementClicked.setAttribute('listener', 'true');
console.log('event has been attached');
});
}
Creating a special attribute for an element when the listener is attached and then checking if it exists.
There is no way to check whether dynamically attached event listeners exist or not.
The only way you can see if an event listener is attached is by attaching event listeners like this:
elem.onclick = function () { console.log (1) }
You can then test if an event listener was attached to onclick
by returning !!elem.onclick
(or something similar).
What I would do is create a Boolean outside your function that starts out as FALSE and gets set to TRUE when you attach the event. This would serve as some sort of flag for you before you attach the event again. Here's an example of the idea.
// initial load
var attached = false;
// this will only execute code once
doSomething = function()
{
if (!attached)
{
attached = true;
//code
}
}
//attach your function with change event
window.onload = function()
{
var txtbox = document.getElementById('textboxID');
if (window.addEventListener)
{
txtbox.addEventListener('change', doSomething, false);
}
else if(window.attachEvent)
{
txtbox.attachEvent('onchange', doSomething);
}
}