I know that you can add new jQuery functions by $.fn.someFunction = function()
However, I want to add functions to specific elements only. I tried this syntax and it doesn't work $('.someElements').fn.someFunction = function()
I want to do this so that I can call the function like this somewhere in the code $('someElements').someFunction();
For jQuery 1.7 and later, use .on() and .trigger()
$('button').on('someFunction',function() {
alert('go away!')
});
$('button').click(function(){
$(this).trigger('someFunction');
});
Before jQuery 1.7 we used .bind() method for attaching event handlers (instead of .on()).
yo can do the above with this:
$.fn.testFn = function(){
this.each(function(){
var className = $(this).attr('class');
$(this).html(className);
});
};
$('li').testFn(); //or any element you want
Yo, needed to do the same thing, came up with this. its nice cause you destroy the element and function goes poof! I think...
var snippet=jQuery(".myElement");
snippet.data('destructor', function(){
//do something
});
snippet.data('destructor')();