Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a link click with custom attributes with jQuery?

Tags:

jquery

I have some links like this:

<a href="#" track="yes">My Link</a>

How can I detect when a link with the track attribute is clicked ?

Thanks!

like image 542
Mateo Avatar asked Dec 17 '10 10:12

Mateo


2 Answers

Use the attribute selector:

$("a[track]").click(function(e){
  // Your code
});

Example: http://jsfiddle.net/jonathon/uXwSF/

As andre points out in the comments, if you want to get only links where track='yes' then do:

$("a[track='yes']").click(function(e){
  // Your code
});

If you want to get all links with the track attribute, but know what the value is then:

$("a[track]").click(function(e){
  var shouldTrack = $(this).attr('track');
});
like image 146
Jonathon Bolster Avatar answered Nov 03 '22 01:11

Jonathon Bolster


$("a[track]").click(function()
{
    ...
});

This will bind a click event to every link with a track attribute.

An even better solution is to use live to limit the number of event handler:

$("a[track]").live("click", function()
{
    ...
});
like image 44
Vincent Robert Avatar answered Nov 03 '22 01:11

Vincent Robert