Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Plugin Function Call With .On

Tags:

jquery

dynamic

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?

like image 954
daveywc Avatar asked Apr 18 '26 05:04

daveywc


2 Answers

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

like image 68
Chamika Sandamal Avatar answered Apr 20 '26 19:04

Chamika Sandamal


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();
like image 37
mrtsherman Avatar answered Apr 20 '26 17:04

mrtsherman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!