Passing variable to window.location href

Johan Dahl picture Johan Dahl · Feb 13, 2013 · Viewed 9.8k times · Source

I'm trying to delay outgoing links when clicked, so that googles event tracking have time to occur.

I wrote the following code, but I'm unsure of how to pass my variable to window.location. It just adds it as string "url" and not the link adress. What am I doing wrong?

$("a.private-product-order-button").click(function(e) {
   e.preventDefault();
   _gaq.push(['_trackEvent', 'Order buttons', 'Click', 'Service']);
   var url = $(this).attr("href");
   setTimeout(function() {
      $(window.location).attr('href', 'url');
      }, 200);
});

Answer

dfsq picture dfsq · Feb 13, 2013

No need to use jQuery to set a property of the location object (and no need to use jQuery to get href property of the anchor object):

$("a.private-product-order-button").click(function(e) {
    e.preventDefault();
    _gaq.push(['_trackEvent', 'Order buttons', 'Click', 'Service']);

    var url = this.href;
    setTimeout(function() {
        window.location.href = url;
    }, 200);
});