Over a million developers have joined DZone.

Are You Leaving my Site?

DZone 's Guide to

Are You Leaving my Site?

· Web Dev Zone ·
Free Resource
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...

        attr("title","Opens new window").
        click(function(e) {
            alert('You are leaving mysite and going somewhere else, you crazy dude')

Try it out...

An explanation of the code:


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. 


is a browser standard to open a new window. 


is the JQuery method whichs binds custom event handler to the the JavaScript "click" event. 



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}