I have a function that I am calling with two images like so.
$('#image1').bind('click',doNext);
$('#image2').bind('click',doNext);
I need to be able to tell which one called the function.
function doNext(){
if(target == $('#image1'){
alert('image1');
}else{
alert('image2');
}
}
thiswithindoNextwill be the raw DOM element, so:There I’m branching on the
idbecause you specifically did that in your code, but usually you just interact with the object.If you need to use any jQuery functions, wrap the raw DOM element in a jQuery object (
var $this = $(this);), but you don’t need to if all you want to do is look at theidas I did above.Within jQuery event handlers, there are (at least) two significant DOM elements you have access to: The element on which you hooked the event (
this), and the element that triggered the event (event.target). In your case, assuming thatimage1andimage2areimgelements, they’ll be the same becauseimgcan’t contain any other element, but in the case of elements that can contain other elements (div,p, etc. — e.g., most elements),event.targetmay be different fromthis. Say you have:and this
If you click the paragraph, you’ll get
…because you hooked the event on the
div, but it was triggered by a click on thep. (This is the basis of event delegation.)