23

Possible Duplicate:
Selecting element by data attribute

I'm trying to listen to when an element with a certain data attribute is clicked but I can't seem to get the on click working and I'm sure its something easy on my part that I'm missing. I have

<a href="/home" data-spinner="true" />
$.data('record').click(function() {
         //Do Action
});

I have that with variations. My question is, how can I use an data attribute with on click?

Community
  • 1
  • 1
Devin Dixon
  • 11,553
  • 24
  • 86
  • 167
  • 5
    This is not how `$.data` works. I recommend to read the documentation, before you blindly try things: http://api.jquery.com/jQuery.data/. It saves a lot of time! – Felix Kling Nov 19 '12 at 00:00

3 Answers3

50

Easy solution to your problem: (Not tested)

$('a[data-spinner="true"]').click(function(event) {

});
Robin Jonsson
  • 2,761
  • 3
  • 22
  • 42
  • $('a[data-spinner="true"]').on('click', function(){ }); or $(document).on('click', 'a[data-spinner="true"]', function(){ }); if html dynamically added to DOM – Hau Le Jun 20 '23 at 01:54
22

This selects all elements with the data-spinner attribute, regardless of the value of the attribute.

    $( "[data-spinner]" ).live( "click", function () {
        console.log('clicked');
    } );
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • `.live()` removed from later versions of jQuery, use `.on()` instead; https://api.jquery.com/on/ – bot19 Sep 02 '22 at 01:16
12

The following code binds click event to all <a> elements which have data-spinner attribute equal to true:

$("a[data-spinner='true']").click(function() {
    //Do Acction
});
VisioN
  • 143,310
  • 32
  • 282
  • 281