ndisdabest
ndisdabest

Reputation: 329

Find links with certain class and add javascript to link

Trying to do two things:

1) Look for links that have the class "download" attached. 2) If so, add some Google Event Tracking code to the link

As a means of testing, here's what I have thus far:

​<a href="#" class="download">Test</a>

$(document).ready(function(e) {
if ($(a).is('.download')){
        $(a).append('onclick="_gaq.push(['_trackEvent', 'Podcasts', 'Download', 'Title']);"');
        }
}

Can't seem to get this to work, althought I think (hope) I have the right idea. Any suggestions?

Thanks in advance!

Upvotes: 1

Views: 407

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Use the class selector instead of is(). Also your code will give js error because a is not defined as there are not quotes around it so it will be treated as a variable which is not defined.

$(document).ready(function(e) {
    $('a.download').click(function(){
         _gaq.push(['_trackEvent', 'Podcasts', 'Download', this.href]);
         return false;
    });
});

Class selector reference - http://api.jquery.com/class-selector/

As a side note is() checks the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

Upvotes: 1

moribvndvs
moribvndvs

Reputation: 42497

$(function() {
   $('a.download').click(function(e) {
    e.preventDefault();
     var $a = $(this);
      // $a is the anchor that was clicked. you can access attributes or its text to populate the _gaq.push call below.  e.g. var text = $a.text();
     _gaq.push(['_trackEvent', 'Podcasts', 'Download', $a.attr('href')]);
   });
});

Upvotes: 2

Frederick Behrends
Frederick Behrends

Reputation: 3095

$('.download').on('click', function(){
          _gaq.push(['_trackEvent', 'Podcasts', 'Download', 'Title']);
        });

This should do what you want.

Upvotes: 0

Related Questions