Patrick
Patrick

Reputation: 5592

How can i bind an extra click event to a hyperlink using jQuery 1.4?

I need to loop trough all email-links on a webpage. Then add GA tracking to each one of them. So below i have just been testing to get the binding to work, but that fails for some reason and tried to open the email client when i view the page.

var emails = $('a[href^="mailto:"]');
for (var i = 0; i < emails.length; i++){
    var email = emails[i];
    email.click(function(e) {
        e.preventDefault();
        alert('test');
        //_gaq.push(['_trackEvent', 'Emails', $(this).pathname]);
    });
}

Right now i want the popup to appear when i click the link, but it's not working.

Upvotes: 0

Views: 74

Answers (2)

Nagendra Rao
Nagendra Rao

Reputation: 7152

You can use $.each something like this.

$( 'a[href^="mailto:"]' ).each(function() {
    $( this ).click(function(){
       e.preventDefault();
       alert('test');
       //_gaq.push(['_trackEvent', 'Emails', $(this).pathname]);
    });
});

Upvotes: 0

Mister Epic
Mister Epic

Reputation: 16713

This would be more direct:

  $('a[href^="mailto:"]').click(function(e){
       e.preventDefault();
       alert('test');
  })

jQuery masquerades as an array of the elements its selector selects. By applying a handler to the jQuery object in this fashion, it actually attaches the handler to all elements that satisfy the selection criteria.

Upvotes: 3

Related Questions