Alex Staveley is a software professional passionate about software engineering and technical architecture. He blogs about architectural approaches, Java topics, web solutions and various technical bits and pieces. Alex is a DZone MVB and is not an employee of DZone and has posted 37 posts at DZone. You can read more from them at their website. View Full User Profile

Are You Leaving my Site?

08.23.2012
| 1416 views |
  • submit to reddit
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...

<script>
    $("a[href^='http://']:not([href*='"+location.hostname+"']),
        [href^='https://']:not([href*='"+location.hostname+"'])").
        attr("target","_blank").
        attr("title","Opens new window").
        click(function(e) {
            alert('You are leaving mysite and going somewhere else, you crazy dude')
        });
</script>

Try it out...

An explanation of the code:

:not([href*='"+location.hostname+"'])

means match elements that do not match the window.location.host property. Don't forget jquery provides many powerful selection 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. 

 

Published at DZone with permission of Alex Staveley, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)