Friday, September 21, 2018

Determining the Element Clicked on in jQuery

In jQuery, you can easily find out when an element itself is clicked on, but binding with the click event, like so...

$('#MyElement').click(function(event) {
console.log("I just clicked the element with the id of Myelement!");
});

But in more complicated scenarios, several elements will trigger a shared function, and you need to know which element was clicked from that shared function.

That would be like this...

$('#MyElement').click(function(event) { return doSomething(event);}
$('#MyOtherElement').click(function(event) { return doSomething(event);}

In this case, you could find out which element was clicked by using the event object...

function doSomething(event) {
console.log("Just clicked the element with an id of..." + event.target.id);
}

The event.target object will tell you almost everything you need to know about what was clicked.

No comments:

Post a Comment