Getting Better Data From Your Links

jquery logo

jQuery- write less.do more

It’s late, but I just finished up a fun little web analytics project that I think a lot of people could use. It’s not very sexy, but especially if you use Google Analytics, read on.

I wanted to track traffic from two sister sites that link back to the main e-commerce site more accurately. I decided that appending some traffic parameters to the links was the way to do it. So instead of having a link that looks like this:

<a href="http://www.example.com/page.html">Awesome Page</a>

it would look like this:

<a href="http://www.example.com/page.html?utm_source=blog&amp;utm_medium=content&amp;utm_content=text&amp;utm_campaign=editorial">Awesome Page</a>

The advantage to having links like this is that they will allow you to collect more and better data. You can learn about building smarter links here.

So the down side was, nobody wants to have to write all that junk after every link. So as usual, my go-to javascript framework jQuery saved me. I’m no jQuery guru like my friend Lucas Myers (who runs an awesome javascript meetup), but I can usually get something working.

So I added this to my global footer of the site:

<script type="text/javascript">
        $(document).ready(function(){
            $('a').filter('[href^=http://www.example.com]').each(function () {
                var href = $(this).attr('href');
                $(this).attr('href', href + '?utm_source=blog&utm_medium=content&utm_campaign=editorial');
            });
        });
    </script>

Those 6 lines of javascript is actually a jquery call, that waits for the dom to finish loading, then walks through the page, finds only the links that begin with http://www.example.com, and appends our super-duper tracking code to them.

Done!

Easy solutions like this make web development a lot easier.

Note: you need to invoke the jquery framework up in the head of your document.

Comments

  1. Truly awesome. Thank you for sharing!

Leave a Reply

css.php