Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append an onClick event to an anchor tag using jquery?

I am trying to add an onClick event to an anchor tag ...

Previously i had ...

<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">

But i am trying to avoid the inline onClick event because it interferes with another script..

So using jQuery i am trying the following code ...

<script>
    $(document).ready(function() {
      $('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
        pageTracker._link(this.href); 
        return false;
      });
    });
</script>

with the html like so <a id="tracked" href="something.html">

So my question is should this be working, and if not what would be the best solution?

like image 454
Matthew Woodard Avatar asked Jun 16 '10 22:06

Matthew Woodard


1 Answers

The correct way would be (as for jQuery)

$('#tracked').click(function() {
    pageTracker._link($(this).attr('href'));

    return false;
});

This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.

As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:

$('#tracked').click(function() {
    $(this).attr('onclick', 'pageTracker._link(this.href); return false;');

    return false;
});
like image 152
realshadow Avatar answered Nov 10 '22 04:11

realshadow