If I have a jQuery plugin as follows:
(function($)
{
$.fn.somefunction = function(text, options){
...function code goes here
};
$('.selector_name').somefunction();
})(jQuery);
How do I cause it to be bound with the .on function so that it will run for dynamically loaded elements.
I have tried:
(function($)
{
$.fn.somefunction = function(text, options){
...function code goes here
};
$('.selector_name').on.somefunction();
})(jQuery);
but that gives me a JScript runtime error: "Object doesn't support property or method 'somefunction'.
How should I be doing this?
on is valid only for events. you can bind it to custom event as well.
$('.selector_name').on("somefunction", function(){
****
});
but you have to trigger it again
$('.selector_name').trigger("somefunction");
http://api.jquery.com/on/
working sample
If you want to bind your function to dynamically loaded elements then do it when they are added.
var $newElem = $('div');
$newElem.somefunction();
on binds to events, not to functions.
$(selector).on('click', function() { ... });
There is no 'on element created' method in jQuery. When you are adding them you will need to do the work of binding to them if need be.
//load some content via ajax
$('div').load('foo.html');
//rebind your function if need be
$('div').children('span').somefunction();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With