Ibolit Ibolit - 1 year ago 51
jQuery Question

jQuery, bind custom functions to DOM elements

I have two divs in my app and I want them to have custom functions with the same signature, but with different actions, so that I could store the "current" div in a variable, and just call something like:


myCurrentDiv.theFunction(someEventData);

and have the corresponding methods fired up.

How can I do that using jQuery?

I tried doing something like:

$("#myFirstDiv").theFunction = function() {
alert("theFunction on firstDiv");
}
$("#mySecondDiv").theFunction = function() {
alert("theFunction on secondDiv");
}

Answer Source

jQuery's philosophy is opposite to what you want: jQuery doesn't extends any existent types/objects with new attributes or methods; it implements all inside itself.

But if you want to do it with jQuery, you have few different ways:

  1. JavaScript way:

    $("#mySecondDiv")[0].theFunction = function(a, b) { /* ... */ }
    
  2. jQuery.data:

    $("#mySecondDiv").data({ theFunction: function(a, b) { /* ... */ } });
    $("#mySecondDiv").data("theFunction")(1, 2)
    
  3. Custom event:

    $("#mySecondDiv").bind('my-event', function(event, a ,b) { /* ... */ });
    $("#mySecondDiv").trigger('my-event', [1, 2]);
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download