Skip to main content

Adding an external link message to all links with jQuery

Learn how to show a message to the user whenever he clicks in a link pointing to a different website

Posted in jQuery, Code snippets, Tutorials, JavaScript

Sometimes we face some situations where we have to tell the user he is leaving our website. This can be achieved with CSS selector without so much problem. But what if the external link is in a button? For that situation we should use JavaScript.

Let's see how to do it in this very short tutorial.

Objective

We need to create a script where a message will be shown whenever the user clicks in some link which will lead him outside of the website. And this must be done unobtrusively.

The foundation

First we need to prepare the foundation of our code. Given the objective we will need to:

  1. Loop through all "a" elements
  2. Get the href value
  3. Compare if the host matches with the href host
  4. Assign the click button

1. Loop through all "a" elements

Since we are using jQuery we can make use of the jQuery.each(), as seen below, to loop through all "a" elements:

$('a').each(function () {
// something
});

2. Get the href value

This is a bit trickier but, to make it easier, we will create a function to do the job:

var getLocation = function (href) {
	var l = document.createElement("a");
	l.href = href;
	return l;
};

And we will call it like this:

var a = getLocation($(this).attr('href'));

3. Compare if the host matches with the href host

var retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf('mailto') == -1;

Here you have to use a set of rules which will make the code work properly. For the sake of the example I’ve decided to keep it simple, but you can (and should) extend according to your project. 

4. Assign the click button

For those who are already aware of jQuery this is an easy piece. But I will leave it here anyway.

if (retValue === true) {
	$(this).on('click'function () {
		// something
	});
}

Now that we have the foundation ready you can see it working in this JSFiddle. When you click the links you will see that one of them shows an alert() message. Now the things will get more interesting, by implementing our confirmation message. 

Showing the message

Now that we have everything in place we can start to work with the message. For this example I will keep it simple and use a simple confirm(), as seen below:

return confirm('Do you really want to leave this website and go to ' + a.href + '?');

Conclusion

Here is the whole code:

var getLocation = function (href) {
	var l = document.createElement("a");
	l.href = href;
	return l;
};
$(function () {
 
	$('a').each(function () {
		var a = getLocation($(this).attr('href'));
 
		// IE fix
		a = getLocation(a.href);
 
		var retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf('mailto') == -1;
 
		if (retValue === true) {
			$(this).on('click'function () {
				return confirm('Do you really want to leave this website and go to ' + a.href + '?');
			});
		}
	});
 
});

As you can see it is very simple to make and even simpler to use. Once you call it in all pages it will scan all your links and check if they should have this extra event or not. Also, for most of the projects we don’t need more than this. And when you have the need of more customization (Bootstrap Modal or jQuery UI Dialog) you can just replace the confirm() by something else.

I will show how to do it in the future articles.

EDIT: I've made a small change on the script (bold, see above) as IE11 had some problems to get the a.hostname.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Horizontal scrolling with jQuery

Learn how to easily make horizontal anchors with jQuery

Posted in jQuery, Code snippets, Tutorials, JavaScript

I've got a freelance job from a Brazilian company few days ago. The project is fine, nothing so different than the usual. Except for one thing: They want the page to scroll horizontally.

The clients are getting creative these days...

My biggest problem is the main menu: If the page would be normal I could use anchor. But I can't since anchors don't work on the horizontal.

Fortunatelly the solution is easy: .scrollLeft()

What .scrollLeft() does is simple: It returns the position of the horizontal scroll bar. And if we pass a parameter it will set the scroll bar where we want.

I have an example on how it's done. Let's walk through it:

HTML

Very simple, no problem at all. Only one navigation and a couple of divs just to give something to work with:

<header>
    <nav>
        <ul>
            <li><a class="nav-item1" href="#">Item 1a>li>
            <li><a class="nav-item2" href="#">Item 2a>li>
            <li><a class="nav-item3" href="#">Item 3a>li>
        ul>
    nav>
header>
<section>
    <div class="item item1">Item 1div>
    <div class="item item2">Item 2div>
    <div class="item item3">Item 3div>
section>

CSS

The CSS is very basic, just to give some formatting:

<style type="text/css">
    nav { position: fixed; z-index: 1030; }
    section { width: 3600px; top: 100px; position: relative; overflow: auto; }
    .item{ float: left; position: relative; width: 900px; height: 500px; font-size: 200px; }
    .item1 { background: #f00; }
    .item2 { background: #0f0; }
    .item3 { background: #00f; }
style>

Javascript

Since we have 3 items I've created a function which groups everything. In that way I am able to keep the code clean, without repeating important parts:

function horizontalNavigation(position, event) {
    $('html').scrollLeft(position);
    event.preventDefault();
}

And here is where the magic happens:

$('.nav-item1').click(function (event) {
    horizontalNavigation(0, event);
});
$('.nav-item2').click(function (event) {
    horizontalNavigation(900, event);
});
$('.nav-item3').click(function (event) {
    horizontalNavigation(1800, event);
});

See the working example.

There is only one problem with this code: What if I want to have a smoothly horizontal scrolling? For that we can use .animate(). Solution in bold bellow:

function horizontalNavigation(position, event) {
    $('html').animate({scrollLeft: position}, 800);
event.preventDefault(); }

See the working example.

As you can see it is not so complicated as it looks. Just a bit of work, but quite easy.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to uncheck all radio buttons and checkboxes using jQuery

Learn how to use jQuery to reset all radio buttons and checkboxes AT ONCE in a page

Posted in jQuery, Code snippets, Tutorials, JavaScript

- UPDATE -

My friend Wellington sent me this code right after I've published this post:

$('input:checked').removeAttr('checked');

This should get all the checked items and remove the "checked" attribute.

- Original post -

Recently I have come across a very interesting problem in a project I am working on. I had to uncheck all checkboxes at once. It was fine by using a simple .each on jQuery. After that the requirements changed and I had to add radio buttons and they weren't working with the code I already had. That was fixed with one more line. Let's see how it was done.

Suppose I have 3 checkboxes and I want to clear all of them at once. Normally I would do something like this:

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
	})
});

Very simple, very generic and it works like a charm. However, suppose that I have to add some radio buttons. The code above will not work with radio buttons, as mentioned before. If you want to uncheck all the radio buttons and checkboxes you will need to add one single line (in bold):

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
		$('input[type="radio"]').prop('checked'false);
	})
});

According to jQuery website the .prop is gets the value of a property for the first element in the set of matched elements or set one or more properties for every matched element. In another words it will look for the "checked" property and, if you want, it can change its value as well.

Easy, simple and clean.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network: