Matthew Woodard
Matthew Woodard

Reputation: 754

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?

Upvotes: 9

Views: 48645

Answers (3)

TimSmith-Aardwolf
TimSmith-Aardwolf

Reputation: 544

I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.

$( window ).ready(function() {
  $('#containerDiv a').click(function() {
    dataLayer.push({
      'event': 'trackEvent',
      'gtmCategory': 'importantLinkSimilarProperties',
      'gtmAction': 'Click',
      'gtmLabel': $(this).attr('href')
    });
  });
}); 

Upvotes: 1

user2240271
user2240271

Reputation: 21

You can also try

var element1= document.getElementById("elementId");

and then

element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");   

// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()

Upvotes: 2

realshadow
realshadow

Reputation: 2585

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

Upvotes: 15

Related Questions