Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, bind custom functions to DOM elements

Tags:

jquery

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");
}

like image 367
Ibolit Avatar asked Aug 08 '11 13:08

Ibolit


3 Answers

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]);
    
like image 96
Rost Avatar answered Sep 17 '22 17:09

Rost


You can use jQuery.data to store data associated with a specific element.

For example:

var div = $("#myFirstDiv")[0];
jQuery.data(div, "theFunction", function() {
    alert("theFunction on firstDiv");
});
like image 32
Justin Ethier Avatar answered Sep 18 '22 17:09

Justin Ethier


Looks like what you want is a custom event in jquery...

$('#myFirstDiv').bind('theFunction', function(e) {
  alert('theFunction on firstDiv');
});

$('#mySecondDiv').bind('theFunction', function(e) {
  alert('theFunction on firstDiv');
});

$('#myFirstDiv').trigger('theFunction');

Here's a working fiddle to show you the example: http://jsfiddle.net/XkutP/

like image 3
Jeff Avatar answered Sep 17 '22 17:09

Jeff