tags:

views:

438

answers:

5

How do you copy an event handler from one element to another? For example:

$('#firstEl')
    .click(function() {
        alert("Handled!");
    })
;

// here's where the magic happens 
$('#secondEl').click = $('#firstEl').click; // ????

Note that the second element is being processed at a different time to when the first element is getting its handler, meaning that this:

$('#firstEl, #secondEl').click(function() { ... });

...won't work.

+2  A: 

You can't easily (and probably shouldn't) "copy" the event. What you can do is use the same function to handle each:

var clickHandler = function() { alert('click'); };
// or just function clickHandler() { alert('click'); };

$('#firstEl').click(clickHandler);

// and later
$('#secondEl').click(clickHandler);

Alternatively you could actually fire the event for the first element in the second handler:

$('#firstEl').click(function() {
    alert('click');
});

$('secondEl').click(function() {
    $('#firstEl').click();
});

Edit: @nickf is worried about polluting the global namespace, but this can almost always be avoided by wrapping code in an object:

function SomeObject() {
    this.clickHandler = function() { alert('click'); };
}
SomeObject.prototype.initFirstEvent = function() {
    $('#firstEl').click(this.clickHandler);
};
SomeObject.prototype.initSecondEvent = function() {
    $('#secondEl').click(this.clickHandler);
};

or wrapping your code in an anonymous function and calling it immediately:

(function() {
    var clickHandler = function() { alert('click'); };
    $('#firstEl').click(clickHandler);
    $('#secondEl').click(clickHandler);
})();
Prestaul
ah yes that would work, but I was hoping for a method which wouldn't pollute the global namespace.
nickf
@nickf: I've edited my post in response to your concern.
Prestaul
+1  A: 

Is this what you are looking for?

var clickHandler = function() { alert("Handled!"); }
$('#firstEl').click(clickHandler);
$('#secondEl').click(clickHandler);
Beau Simensen
A: 

$('#secondEl').click = $('#firstEl').click.bind($('#secondEl'));

Assuming you are using Prototype JS (http://www.prototypejs.org/api/function/bind)

TRF
Even with Prototype.js there is no .click property...
Prestaul
A: 

You might be interested in the triggerHandler method

// here's where the magic happens 
//$('#secondEl').click = $('#firstEl').click; // ????
$('#secondEl').click(function() {
    $('#firstEl').triggerHandler('click');
});
Ken Browning