What is the jQuery equivalent code for the following JavaScript that saves onclick events?

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 am wondering what is the jQuery equivalent for the code above?

Thanks!

+2


a source to share


3 answers


var someObj = $("#foo").get(0);
var fooClick = someObj.onclick;

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

      

or if you want it on one line:



$("#bar").click($("#foo").get(0).onclick);

      

+5


a source


Is it really required that you get the event handler from another object? That doesn't sound like a great idea to me. Your best bet would be to define a handler and assign it to both objects.



var clickHandler = function(e) { alert('click!'); };
$('#foo,#bar').click(clickHandler);

      

+6


a source


By simply adding the answer to Daniel Schaffer (+ 1'd), you can also include the definition of your "handler" click, for example:

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

      

The behavior should be the same, but depending on your coding style, you may prefer this (s).

+3


a source







All Articles