How to Check Whether Dynamically Attached Event Listener Exists or Not

How to check whether dynamically attached event listener exists or not?

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).

Check if an element has event listener on it. No jQuery

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: How to check whether dynamically attached event listener exists or not?

Check if input has onchange listener and call it manually

You seem to be over-thinking the problem a little. You don't need to check if the event handler is bound at all. If you trigger the event and a handler is bound, then your logic will execute. If you trigger the event and no handler is bound, nothing will happen.

Therefore you can just raise the event using change() or trigger('change') regardless.

$('#input-address').trigger('change');

Is there a way to dynamically name event handlers in JavaScript?

You can programmatically create the buttons and/or add an eventlistener like so:

const buttonContainer = document.getElementById('button-container');
const target = document.getElementById('target');

const colors = [ "red", "blue", "yellow" ];

for (const color of colors) {
const colorButton = document.createElement('button');
colorButton.innerText = color;
colorButton.addEventListener('click', () => {
target.style.backgroundColor = color;
});
buttonContainer.appendChild(colorButton);
}
#target {

width: 200px;
height: 200px;
background-color: red;
}
<div id="button-container"></div>
<div id="target"></div>

dynamically created button onclick is not working in react js

this is issue with insertAdjacentHTML i used React.createElement and after rendered using ReactDOM.render

let input = React.createElement("input",{className:"questionTextInput",name:"textInputQuestion[]"},null);
ReactDOM.render(input,questionPreview);


Related Topics



Leave a reply



Submit