Jonathan Sayce Jonathan Sayce - 1 year ago 86
Javascript Question

jQuery - Event extension to get event target or parent of specific type

Using a glyph library like Font Awesome, buttons often end up looking something like this:

<span class="fa fa-stack-overflow fa-lg"></span> Click me

When handling a button event, the target can be either the span or the button itself, depending on where the user clicks, so I normally end up with something like this:

$('button').on('click', function($event) {

var $target = $($;
var $button = $'button') ? $target : $target.closest('button');

// useful stuff goes here

Is it possible to extend the jQuery event object to add a method that encapsulates this functionality, so it can be called like this?

var $button = $event.getSpecificTarget('button');

I've created a JSFiddle to demonstrate the issue.

It could be done using a normal jQuery plugin, but it would feel cleaner if it could be accessed straight from the event object, rather than via a plugin like this:

var $button = $.getSpecificTarget($event, 'button');

Answer Source

You can bind the event to the document, instead of what you are doing now.

$(function () {

  $(document).on('click', 'button', function() {
    var button = $(this);
    $('#result').append(button.text() + '<br>');

Please, check this JSFiddle.
You will see that the text of the button is appended to the div when you click the button itself or the span. The key is using $(this).
In fact, you can keep the code as you have it and use $(this) to get the button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download