Archive for April, 2012

Open links in a new window with jQuery

It is possible to open links in a new window by adding target="_blank" to the anchor tag in HTML, but if your page uses the XHTML doctype it will generate a validation error. The following snippet uses JavaScript instead to open the link in a new window, and keeps your XHTML valid.

Make sure you have jQuery loaded, then include this in your JavaScript file:

Now you just need to add rel="external" to any anchor tags that you want to open in a new window (e.g. <a href="somedomain.com" rel="external">some link text</a>).

(Update: Apparently using target="_blank" is valid in HTML5. But this JavaScript method will still work too).

Custom WordPress widget PHP code snippet

Add this to your functions.php file:

Then add this the theme file(s) where you want the Widget to appear:

Now when you go the Widget manager in your WordPress Admin you can add some widgets.

Track PDF downloads with Google Analytics

Use this code to track PDF downloads (or other non-HTML files) with Google Analytics. Be sure to change myfile to your actual filename, both in the url and the tracking code.

Now when the visitor clicks the link to download the file, Google Analytics will record it as a pageview. By prefixing each file name with /downloads/, you can then easily identify and filter these pageviews in your Google Analytics reports.