Jonathan Sayce
Jonathan Sayce

Reputation: 9659

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:

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

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 = $($event.target);
    var $button = $target.is('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');

Upvotes: 1

Views: 60

Answers (1)

Dacklf
Dacklf

Reputation: 700

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.

Upvotes: 1

Related Questions