Displaying alerts on external links with JQuery

jQuery LogoRaymond Camden posted an article this morning on displaying an alert to the user when you click a link that would leave/exit the website. In his example, he suggests adding an extra class to the links that require this feature. In my experience this kind of pop-up confirmation alert when clicking the link is often used by old-school, monolithic institutions or government agencies. But, if you really want or need to annoy your users, here’s a different way to do it that would work on ALL external links from your web page.

First, make sure you’re using relative or absolute paths for your internal links (instead of fully qualified urls). This technique won’t work if you code every link on your site with the http:// in the href attribute.
Next, make sure you’re including the JQuery library on your page.
Then in a <script>, use the following function to target your external links:

$(document).ready(function () {
	$('a[href^="http"]').click(function() {
		return confirm("Are you sure you want to do this?")

Here we’re using a JQuery selector to target external links with this by looking for every instance of “http” in the href attribute of an anchor tag.

This way you do NOT have to add unnecessary, non-semantic code to target external links.

Alternately, if you HAVE coded your links with fully qualified urls, you can substitute the JQuery selector I used above with this one:

	$('a[href^=http]:not("[href*=://' + document.domain + ']")');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s