Add jQuery function to specific elements

JqueryFunctionAdd

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Test: http://jsfiddle.net/DarkThrone/nUzJN/

Solution 3 - Jquery

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

Solution 4 - Jquery

@Reigel's answer is great! However you could also use the $.fn syntax and let your function only handle certain elements:

$.fn.someFunction = function(){
    this.each(function(){
        // only handle "someElement"
        if (false == $(this).hasClass("someElement")) {
            return; // do nothing
        }
    
        $(this).append(" some element has been modified");
    
        return $(this); // support chaining
    });    
};

// now you can call your function like this
$('.someElement').someFunction();            

See working jsfiddle: http://jsfiddle.net/AKnKj/3/

Solution 5 - Jquery

I actually had this use case as well, but with a cached object. So I already had a jQuery object, a toggle-able menu, and I wanted to attach two functions to that object, "open" and "close". The functions needed to preserve the scope of the element itself and that was it, so I wanted this to be the menu object. Anyway, you can just add functions and variables all willy nilly, just like any other javascript object. Sometimes I forget that.

var $menu = $('#menu');
$menu.open = function(){
   this.css('left', 0);
   this.is_open = true; // you can also set arbitrary values on the object
};
$menu.close = function(){
   this.css('left', '-100%');
   this.is_open = false;
};

$menu.close();

Solution 6 - Jquery

If you're wanting this function only for particular selectors, the following will work for you. I've just had a scenario where I've needed this and it works nicely.

$('.my-selector').each(function(){
            
    $(this).init.prototype.getUrl = function(){
        // do things
    };
})

then later on you can do

$('.my-selector').getUrl()

without having to define it as a plugin, or use data or bind/on/trigger events.

Obviously you can change the function to return the containing object if you want to use it in chaining by returning this

$('.my-selector').each(function(){
            
    $(this).init.prototype.getUrl = function(){
        // do things
        return this;
    };
})

Solution 7 - Jquery

The most obvious solution is to assign a function as the object's property:

obj.prop("myFunc", function() {
  return (function(arg) {
    alert("It works! " + arg);
  });
});

Then call it on the object this way:

obj.prop("myFunc")("Cool!");

Note: your function is the return value of the outer one, see: http://api.jquery.com/prop/#prop-propertyName-function

Solution 8 - Jquery

I'm not also sure with my answer if this will help you but just a try how about using .live?

$(selector).live(click,function(){
    //some codes here
});

Solution 9 - Jquery

I did this and its working fine..

 function do_write(){
     $("#script").append("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('Write Your Code here');    });<\/script>");
     console.log("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('hello');    });<\/script>");
}
  

and call function from your dynamic function which is creating a dynamic control in html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2385136View Question on Stackoverflow
Solution 1 - JqueryReigelView Answer on Stackoverflow
Solution 2 - JqueryDarkThroneView Answer on Stackoverflow
Solution 3 - JqueryDrizzelView Answer on Stackoverflow
Solution 4 - JqueryFriederikeView Answer on Stackoverflow
Solution 5 - JquerycharltoonsView Answer on Stackoverflow
Solution 6 - Jquerydan richardsonView Answer on Stackoverflow
Solution 7 - JquerySneghView Answer on Stackoverflow
Solution 8 - JqueryCarls Jr.View Answer on Stackoverflow
Solution 9 - JquerydskView Answer on Stackoverflow