Tuesday, July 24, 2012

Are you leaving my site?

A website will always contain some links. Links fall into one of two categories:
  1. Internal links - links to other parts of your website.
  2. External links - links to other websites external to your website.

There are times when it might make sense to warn the user you are leaving your site. For example, you may have a SAAS style architecture with external links. It is good usability to differentiate links that keep the user on the site and links which will take the user away from the site especially if the latter could invalidate a transaction or session. Even if nothing could become invalidated it must just to differentiate in cases when the site the user will be trvalleing to next is very similar (which might lead the user to think it is the same site), or it might just be nice to say bye.

Well one way you could do this is to use some JQuery to select to all external links and add some JavaScript to execute to warn the user of the results of their action.

Check it out...



Try it out... An explanation of the code:
  • a[href^='http:'
    The ^ after href means means all elements that begin exactly with http:. This is an example of how JQuery builds on CSS selectors.
  • :not([href*='"+location.hostname+"'])
    means match elements that do not match the window.location.host property. Don't forget jquery provides many powerful selection filter expressions using the (:) syntax, Other examples are :first, :odd and :even.
  • ... location.hostname
    is the dom way of figuring out the hostname of your site.
  • attr("target","_blank")
    is a browser standard to open a new window.
  • .click
    is the JQuery method whichs binds custom event handler to the the JavaScript "click" event.