title: Call custom function on dynamically created elements with jQuery
body: <p>I have an external function which has to be called for all elements with a certain class, like this:</p>
  
  <pre><code>jQuery('.myClass').myFunction();
  </code></pre>
  
  <p>This works, but how can I make this happen for dynamically created elements. I have multiple functions which can create elements, and I don't want to add this line in every piece of code which creates a new element.</p>
  
  <p>The reason for this is that i load javascript based on what elements i use with php. I therefore cant add myFunction() to the element create function, since both functions are in different files which might or might not be loaded together on the same page.</p>
  
  <p>So how can I call the <code>.myFunction()</code> function on an object with '.myClass', as soon as it is created.</p>
  
  <p>So in the function that creates the element, i don't know what functions need to be called on the element, and in the file that executes the function on the elements, i don't know which functions create an element.</p>
  
  <p><strong>Solution:</strong>
  Since this is marked as a duplicate question, i cannot add an answer. However, i did take a different approach to solve this than in that question. My approach was creating a new class where every script can add functions which should be called when creating an element, and calling a those functions when creating a new element.</p>
  
  <p>Js:</p>
  
  <pre><code>function jsHandler(){
      this.actions = [];
  
      this.addAction = function(action){
          this.actions.push(action);
          action();
      };
  
      this.callActions = function(){
          jQuery.each(this.actions,function(key,action){
              action();
          });
      };
  }
  var myJsHandler = new jsHandler;//global variable
  </code></pre>
  
  <p>Then in each file which has to call a function over objects, i put this:</p>
  
  <pre><code>myJsHandler.addAction(function(){
      jQuery('.myClass').myFuncion();
  });
  </code></pre>
  
  <p>In every file which creates an element, i put this after creating the element:</p>
  
  <pre><code>myJsHandler.callActions();
  </code></pre>
  
  <p>For me this works. Some notes though:</p>
  
  <ul>
  <li>I probably need to add some code so that jsHandler is always created before the other scripts are loaded.</li>
  <li>Note that this function calls all functions each time an element is created. For my functions this doesn't matter. </li>
  </ul>