Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Are You Leaving my Site?

DZone's Guide to

Are You Leaving my Site?

· Web Dev Zone
Free Resource

Prove impact and reduce risk when rolling out new features. Optimizely Full Stack helps you experiment in any application.

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. 

 

With SDKs for all major client and server side platforms, you can experiment on any platform with Optimizely Full Stack.

Topics:

Published at DZone with permission of Alex Staveley, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}