0

I'm trying to set up a tracking system that uses a data value for holding an event type. My HTML looks like this:

<a href="#articles" class="track" data-track="article_search_results">Articles</a>
<a href="#books" class="track" data-track="books_search_results">Books</a>
<a href="#notes" class="track" data-track="notes_search_results">Notes</a>

And the JQuery looks like this:

$(document).delegate('.track', 'click', function(e) {   
    console.log($(this));
    console.log($(this).data("track")); 
});

Using every element that has the class .track, I'm trying to get the data-track value from it, but it always returns undefined. What am I doing wrong?

UPDATE

I have icons in my code which is causing the problem:

<a href="#articles" class="track" data-track="article_search_results"><i class="icon-pencil"></i></a>
3
  • Your code should work. Commented Mar 29, 2013 at 0:41
  • 1
    jsfiddle.net/kJbjL Commented Mar 29, 2013 at 0:42
  • It does work without the icon..not sure why that is a problem... Commented Mar 29, 2013 at 1:10

2 Answers 2

1

Using attr, you can return the data-track value from an element, for example:

Code:

$(document).on('click', '.track', function(e) {   
    var dataTrack = $(this).attr("data-track");
});

According to the jQuery docs, delegate has been superseded by on, the above is an example using on

Alternatively, in your case, you can probably just use the click function, which I find neater, but up to you:

$(".track").click(function(e) {   
    var dataTrack = $(this).attr("data-track");
});

Fiddle:

Using on:
http://jsfiddle.net/jUSUK/1/

Using click:
http://jsfiddle.net/jUSUK/2/

More info on attr:

http://api.jquery.com/attr/

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

1 Comment

Figured out what the problem is, code is fine by the syntax with an icon isn't
1

Try this

           $(document).delegate('.track', 'click', function(e) {   
                console.log($(this).attr("data-track")); 
           });

JsFiddle: http://jsfiddle.net/FZEKC/

4 Comments

Figured out what the problem is, code is fine by the syntax with an icon isn't
Glad you have figured out the issue yourself
No, the issue still exist, just figured out the problem
why you dont assign the class to anchor instead of <i> tag? try this one <a href="#articles" class="track icon-pencil" data-track="article_search_results"></a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.