1

I'm attempting to create a function that will select all anchor tags with both http and _gaq (because a lot of the links have event tracking on them), and then add Google Analytics cross-domain tracking linker method to the onclick event:

        $("a[href*='http:'][onclick*='_gaq']").each(function(){
            var href = this.href;
            var onclick = $(this).attr('onclick');
            var linker = "['_link', "+ "'"+href+"'"+"],";
            var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');

            console.log('output : '+output);
         });

When I run this, it outputs:

output : _gaq.push(['_link', 'http://google.com'],['_trackEvent','dude','dude','dude']); return false;

This is what I'd like the new value for onclick to be, so I'm wondering how can I have the output value 'overwrite' the old onclick value?

I've also created a jsfiddle to illustrate.

Appreciate any help or suggestions.

Blexy
  • 9,573
  • 6
  • 42
  • 55

2 Answers2

2

Try

$("a[href*='http:'][onclick*='_gaq']").each(function(e){
    var href = this.href;
    var onclick = $(this).attr('onclick');
    var linker = "['_link', "+ "'"+href+"'"+"],";
    var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');
    $(this).attr('onclick', output);
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

I found this question which probably gets you the answer you want:

$("a[href*='http:'][onclick*='_gaq']").each(function(){
     var href = this.href;
     var onclick = $(this).attr('onclick');
     var linker = "['_link', "+ "'"+href+"'"+"],";
     var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');

     $(this).attr('onclick','').unbind('click');  // Get rid of the old one
     var f = new Function(output);                // create a function
     $(this).click(f);                            // Add your new onclick
  });

Edit: I was Led astray by a more recent comment with 26 upvotes. Switching back to my original form.

26 votes Yet it doesn't seem to work!, compare

http://jsfiddle.net/TN2wr/

with

http://jsfiddle.net/TN2wr/1/

Community
  • 1
  • 1
Gus
  • 6,719
  • 6
  • 37
  • 58
  • I appreciate all the documentation and fiddles, but ended up going with @Arun P Johny's answer due to the simplicity. – Blexy Sep 24 '13 at 16:32
  • hmm, as long as you don't care about events added in javascript... http://jsfiddle.net/TN2wr/2/ – Gus Sep 24 '13 at 20:03