NicoF
NicoF

Reputation: 135

How to update an existing a href attribute?

I’m newbie when it comes to jQuery so here is my newbie question ;-) : How to update the existing a href onclick attribute with a new value? I want to insert the Google link-tracker on all existing links. HTML:

<div>
    <a href="http://www.example.com/files/map2.pdf" onclick="dwnlExe();">link</a>
</div>

What I have so far:

<script type="text/javascript">
    jQuery(document).ready(function() {

        var pathName = window.location.pathname
        var n = 1;
        $("a").each(
                function() {
                    if (($(this).attr("onclick")) == undefined) {
                        $(this).attr("onclick", "javascript: pageTracker._trackPageview('" + pathName + "-link-" + n + "');");
                    } else {
                    var onclickValue = $("a").attr("onclick");
                    // how to update the existing onclick="dwnlExe();"
                    // to onclick="dwnlExe(); javascript: pageTracker._trackPageview('" + pathName + "-link-" + n + "');"
                    }
                    n++;
                }
            );
    });
</script>

Upvotes: 1

Views: 268

Answers (1)

FrankBr
FrankBr

Reputation: 237

it would be better to do like this i think:

remove the onclick event, and use javascript to bind the clicks after pageload:

var path = window.location.pathname;
var n = 1;
$('a').each(function() {
  var link = $(this);
  link.bind('click',function() {
    pageTracker._trackPageview( pathName + "-link-" + n);
  });
  if( link.hasClass('dwn') ) {
    link.bind('click',function() {
      dwnlExe();
    });
  }
  n++;
});

the links with both clicks, will trigger both

Upvotes: 2

Related Questions