views:

49

answers:

3

So in JavaScript I can do the following:

var someObj = document.getElementById("foo");
var fooClick = foo.onclick;

var someOtherObj = document.getElementById("bar");
someOtherObj.onclick = fooClick;

I'm wondering, what is the jQuery equivalent to the code above?

Thanks!

+5  A: 
var someObj = $("#foo").get(0);
var fooClick = someObj.onclick;

$("#bar").click(fooClick);

or if you want this in one line:

$("#bar").click($("#foo").get(0).onclick);
David
+6  A: 

Is it really required that you get the event handler from another object? That doesn't seem like a great idea to me. A better way would be to define the handler, and assign it to both objects.

var clickHandler = function(e) { alert('click!'); };
$('#foo,#bar').click(clickHandler);
Daniel Schaffer
I agree with this advice +1, my example gives asker exactly what they asked for, however he/she should consider just binding the same handler to both in the first place as you recommend.
David
Thanks, yours is +1'd for answering the question :D
Daniel Schaffer
Yep, you guys are right... that would be better. However I'm trying save off a click event for an object which renders from the server side with with this click event. So, I have no control over how it renders and can't get the dynamically created javascript until it gets to the client side :(
Polaris878
OOOH that's ugly! My condolences! David's answer is what you're looking for, then
Daniel Schaffer
+3  A: 

Just adding to Daniel Schaffer's answer (+1'd), you can also inline your click 'handler' definition, for example:

$("#foo, #bar").click( function() {
    alert( this.id + ' was clicked.' );
} );

The behaviour should be the same, but depending on your coding style taste, you may prefer this (I do).

dannywartnaby