Add jQuery function to specific elements

user2385136 picture user2385136 · Jan 17, 2011 · Viewed 89.7k times · Source

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();

Answer

Reigel picture Reigel · Jan 17, 2011

Use .bind() and .trigger()

$('button').bind('someFunction',function() {
    alert('go away!')
});


$('button').click(function(){
    $(this).trigger('someFunction');
});

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.