javascriptjqueryevent-listenerdynamicobject

Attach eventListener on dynamically created input text


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


Solution

  • 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 :)