Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  28] [ 4]  / answers: 1 / hits: 47792  / 14 Years ago, wed, june 16, 2010, 12:00:00

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?


More From » jquery

 Answers
89

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;
});

[#96469] Monday, June 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anikas

Total Points: 258
Total Questions: 102
Total Answers: 95

Location: Monaco
Member since Sun, Jan 16, 2022
2 Years ago
;