October 8, 2013

Using .on() and targeting elements with a specific ID

Brandon Durham’s Question:

I understand you can use .on() to attach a single click event to an element and then specify which child elements receive the click. So, for example:

$(this.el).on("click", "span", function () {
    alert("Bloop!");
});

I need to be a bit more specific and target selectors with a particular attribute, like this:

$(this.el).on("click", "span[data-placeholder]", function () {
    alert("Bloop!");
});

That doesn’t seem to work, though. As soon as I add the attribute it stops working. No errors, just doesn’t seem to find the elements.

Is that the expected behavior? Is there a way around it?

CLARITY

$(this.el) is just a div that contains a number of elements, some of which are <span data-placeholder="First Name"></span> tags. There could be dozens of those <span> tags and I didn’t want that many event listeners, so I thought I’d use .on() to add the click to the parent container.

You can choose to filter your spans

$('span', this.el).filter(function() {
     return $(this).hasAttr('data-placeholder');
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

Or if the placeholder is set via data api:

$(this.el).filter(function() {
     return $(this).data('placeholder') != 'undefined';
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

This functions above select those elements specifically, if event delegation on the OP is needed, then you can do the following:

$('span', this.el).on('click', 'span', function() {
     if($(this).data('placeholder') != 'undefined') {
         alert('bloop');
     }
});
...

Please fill the form - I will response as fast as I can!