0

i would like to attach eventListener to dynamically created input Text or other objects. Since the objects are not yet present in the DOM or the objects are not visible, attaching an event to these object fails. There's a proper way in plain Javascript or JQuery to avoid this problem?

Thank you

AmiStack
  • 23
  • 7

1 Answers1

1

in vanilla JS you have to add the event listener to the document and checking the target when something got clicked. If you want to check the class not the id you have to change e.target.id to e.target.className.

 document.addEventListener('click',function(e){
    if(e.target && e.target.id == '{ELEMENT_ID}'){
          //do something
     }
 });

if you programm with jQuery it will be a lot easier, you can add an click handler to the body which ignores everything expect your element id/class which you type into as second parameter (ID = #{ELEMENT_ID}, CLASS = .{ELEMENT_CLASS}

  $('body').on('click','#{ELEMENT_ID}',function() {
    //do something
   })

here is a fiddle with an example for jQuery and vanilla js: https://jsfiddle.net/67m4qr1h/1/

hope this helps :)

Samet Conrad
  • 201
  • 1
  • 5
  • Thank you, very usefull. I knew about this method, but i though it was a bad pratics. I need, by the way to check for the object by name, either js or jquery. Is this methods working for not visible object too? – AmiStack Mar 18 '20 at 10:34
  • Just want to inform that the object are dynamically created after the the document ready. Assuming i press a button that create an input text. I need to attach events the the new input text created. I wonder If it will work if i use the name attribute to attach the events. – AmiStack Mar 18 '20 at 10:45
  • 1
    This will work for every element in the DOM which has the specific class / id. Here is an updated example in jsfiddle https://jsfiddle.net/32s7e1xq/ You should always add eventlisteners with id's or classes not with names. !IMPORTANT! Id's should be unique, so i think in your case you will go with classes. Does this answer your question? – Samet Conrad Mar 18 '20 at 11:33
  • also please take a look into the original stackoverflow question https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Samet Conrad Mar 18 '20 at 11:38
  • Do you confirm that the attribute name is not valid to attach an event? – AmiStack Mar 19 '20 at 21:59
  • 1
    You should not use the name attribute for set eventlisteners to some html tags, if just one element needs a eventlistener use the `#id` oder `#class` attribute, if you want that multiple DOM elements are listening to the same use the `#class` attribute, no need for names tho. – Samet Conrad Mar 20 '20 at 08:49
  • Thank you very much. – AmiStack Mar 25 '20 at 16:51