This is some code of JQuery plugin.
...
return this.each(function(index, el) {
var $this = $(this), data = $this.data('control');
$(el).on('click',el, function(){
alert('hello world!');
});
});
...
I use it so:
$('.mybutton').myPlugin();
Click function normaly work for all elements on page who have .mybutton class, but don't work on ajax loaded elements. Guys, how i can bind click function in JQ plugin for dinamic created elements? Many thanks!
1) If you want a common event-handler for existing and newly created elements use
event-delegation
. The handler is bound to an element higher up in the DOM that always exists, or to the document. Each time an event bubbles up the DOM and reaches the document, the handler looks if the event comes from an element that matches the given selector and only then executes.2) You should set up the handler separately outside your plugin. Otherwise each time you call the plugin a new event-handler is attached, and you get multiple events on one click.
3) If you now use your plugin store the returned object in a variable. If you need it later you don't have to create it a second time, just refer to it by var name.
4) But note this call gets only the buttons that exists in the DOM when its run. If you later get a new element inserted in the DOM and want it added to the buttons-collection you have to do that manually.
If you absolutely want to attach the click-handler inside your plugin it has to look like:
But note now you have to call your plugin on each newly created button.