I have an external function which has to be called for all elements with a certain class, like this:
jQuery('.myClass').myFunction();
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.
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.
So how can I call the .myFunction()
function on an object with '.myClass', as soon as it is created.
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.
Solution: 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.
Js:
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
Then in each file which has to call a function over objects, i put this:
myJsHandler.addAction(function(){
jQuery('.myClass').myFuncion();
});
In every file which creates an element, i put this after creating the element:
myJsHandler.callActions();
For me this works. Some notes though:
- I probably need to add some code so that jsHandler is always created before the other scripts are loaded.
- Note that this function calls all functions each time an element is created. For my functions this doesn't matter.