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?

1
  • 5
    This is not how $.data works. I recommend to read the documentation, before you blindly try things: api.jquery.com/jQuery.data. It saves a lot of time! Commented Nov 19, 2012 at 0:00

3 Answers 3

50

Easy solution to your problem: (Not tested)

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

});
Sign up to request clarification or add additional context in comments.

1 Comment

$('a[data-spinner="true"]').on('click', function(){ }); or $(document).on('click', 'a[data-spinner="true"]', function(){ }); if html dynamically added to DOM
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');
    } );

1 Comment

.live() removed from later versions of jQuery, use .on() instead; api.jquery.com/on
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
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.