1. Code
  2. JavaScript
  3. jQuery

How To Create A Keypress Navigation Using jQuery

Scroll to top
7 min read

The key to a succesful website is the ease with which a user finds what they are looking for. Thus, it's worth spending a lot of time and effort in creating both useful and visually appealing navigation systems. Lately, I have began experimenting with new ways to navigate a website. In this tutorial I'll show you how to let the user make use of their keyboard to get around your site.

Step 1

The first thing we need to do is create our test page. In this case, I will refer to it as demo.html and it will contain the following:

  1. A link to the jQuery framework.
  2. A link to the script we will work on later. Let's call it keypress_nav.js
  3. A link to a CSS file called style.css (we will also work on this later).
  4. A header div that will contain our navigation among other things. And
  5. Five unique div elements that will serve as pages for our site.

So, here is what demo.html looks like at this point:

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
<html>
4
	<head>
5
		<title>KeyPress Navigation Demo</title>
6
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7
		<link rel="stylesheet" type="text/css" href="style.css" />
8
		<script type="text/javascript" src="jquery.js"></script>
9
		<script type="text/javascript" src="keypress_nav.js"></script>
10
	</head>
11
	<body>
12
		<div id="header">
13
			<!-- Our navigation will go here -->
14
		</div>
15
		<div id="home">
16
			<h2>Welcome!</h2>
17
			<p>Some Text</p>
18
		</div>
19
		<div id="about">
20
			<h2>About Me</h2>
21
			<p>Some Text</p></p>
22
		</div>
23
		<div id="contact">
24
			<h2>No Spam Please</h2>
25
			<p>Some Text</p>
26
		</div>
27
		<div id="awards">
28
			<h2>Awards, So Many ...</h2>
29
			<p>Some Text</p>
30
		</div>
31
		<div id="links">
32
			<h2>Cool Sites</h2>
33
			<p>Some Text</p>
34
		</div>
35
	</body>
36
</html>

Step 2

Now that we have our DIVs in place, we can go ahead and create the navigation for the page. As you may have guessed, we will be using an unordered list <ul> to hold the links and the DIV's IDs as the targets for these links. Also, we will add the class container to all the DIV "pages." This class will help us easily refer to these DIVs when we create our script. So, here is what you should have now:

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
<html>
4
	<head>
5
		<title>KeyPress Navigation Demo</title>
6
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7
		<link rel="stylesheet" type="text/css" href="style.css" />
8
		<script type="text/javascript" src="jquery.js"></script>
9
		<script type="text/javascript" src="keypress_nav.js"></script>
10
	</head>
11
	<body>
12
		<div id="header">
13
			<ul id="navigation">
14
				<li><a href="#home">Home ( a )</a></li>
15
				<li><a href="#about">About ( s )</a></li>
16
				<li><a href="#contact">Contact ( d )</a></li>
17
				<li><a href="#awards">Awards ( f )</a></li>
18
				<li><a href="#links">Links ( g )</a></li>
19
			</ul>
20
		</div>
21
		<div id="home" class="container">
22
			<h2>Welcome!</h2>
23
			<p>Some Text</p>
24
		</div>
25
		<div id="about" class="container">
26
			<h2>About Me</h2>
27
			<p>Some Text</p></p>
28
		</div>
29
		<div id="contact" class="container">
30
			<h2>No Spam Please</h2>
31
			<p>Some Text</p>
32
		</div>
33
		<div id="awards" class="container">
34
			<h2>Awards, So Many ...</h2>
35
			<p>Some Text</p>
36
		</div>
37
		<div id="links" class="container">
38
			<h2>Cool Sites</h2>
39
			<p>Some Text</p>
40
		</div>
41
	</body>
42
</html>

Note: The letter (key) inside the parenthesis is the key we will later use as navigation for our page.

Step 3

The structure of our test page is now complete but lacking visual appeal. So, let's add some CSS and jazz it up. One thing to keep in mind before we begin the styling is that our page must look good even if JavaScript is turned off. Scripts, in my opinion, should always be used as a bonus to those users who have JavaScript turned on but should not alienate those who don't. We are web designers/developers after all, and we care about usability, right?

You can see the look we're going for in the screenshot above. It's simple and uses some nice, bold colours to highlight the different sections. So here's our CSS:

1
body 
2
{
3
	margin: 0;
4
	padding: 0;
5
	font-family: "Lucida Grande", "Lucida Sans", sans-serif;
6
	font-size: 100%;
7
	background: #333;
8
}
9
10
11
/* Header
12
-------------------------------------------------- */
13
14
#header
15
{
16
	width: 460px;
17
	margin: 0 auto;
18
	font-size: .75em;
19
	font-family: "Helvetica Neue", Helvetica, sans-serif;
20
}
21
22
#header ul 
23
{
24
	list-style: none;
25
	margin: 0;
26
	padding: 0;
27
}
28
29
#header ul li 
30
{
31
	float: left;
32
	text-align: left;
33
}
34
35
#header ul li a
36
{
37
	display: block;
38
	color: #ffff66;
39
	text-decoration: none;
40
	text-transform: uppercase;
41
	margin-right: 20px;
42
}
43
44
#header ul li a:hover
45
{
46
	text-decoration: underline;
47
	color: #ffcc66;
48
}
49
50
51
/* Containers
52
-------------------------------------------------- */
53
54
.container
55
{
56
	width: 400px;
57
	height: 300px;
58
	margin: 30px auto;
59
	padding: 10px 20px;
60
	border: 10px solid #fff;
61
	color: #fff;
62
	font-size: .75em;
63
	line-height: 2em;
64
}
65
66
.container h2
67
{
68
	padding: 5px 10px;
69
	width: 200px;
70
}
71
72
#home		{ background: #15add1; }
73
#home h2	{ background: #007aa5; }
74
#about		{ background: #fdc700; }
75
#about h2	{ background: #bd9200; }
76
#contact	{ background: #f80083; }
77
#contact h2	{ background: #af005e; }
78
#awards		{ background: #f18300; }
79
#awards	h2	{ background: #bb5f00; }
80
#links		{ background: #98c313; }
81
#links h2	{ background: #6f9a00; }
82
83
84
/* Self-Clearing Rules 
85
-------------------------------------------------- */
86
87
ul#navigation:after 
88
{
89
    content: ".";
90
    display: block;
91
    visibility: hidden;
92
    clear: both;
93
    height: 0;
94
}
95
96
* html ul#navigation 	{ height: 1px; }
97
ul#navigation 			{ min-height: 1px; }

Note: I have added some self-clearing rules to the navigation in order to work around its lack of height due to its inner floated elements. In other words, margin rules from the upper most container will now have the proper effect on the navigation <ul>.

Step 5

At this point in the tutorial you should have a page looking something like this:

Test Page Preview

It is a functional page and it works properly without the need for JavaScript to be turned on. However, as I said before, let's give a little bonus to those users who do have JavaScript turned on on their browsers. We will do this in two steps. Firstly, we will create two functions that will hide and display the pages appropiately. And secondy, we will add some some code to determine the keys pressed by the user. Let's now create a file called keypress_nav.js and get to work on our functions.

Step 6

We are going to need two functions for our script to work as desired. One of the functions will be called when the user presses one of our predetermined navigation keys (The letters in parenthesis from Step 2) and will hide all other containers displaying only the DIV associated to this key. This is what our first function looks like:

1
function showViaKeypress(element_id)
2
{
3
	$(".container").css("display","none");
4
	$(element_id).slideDown("slow");
5
}

Now, our second function will take an array of links and assign them on click target functions. In other words the function will get our navigation links, retrieve the "href" attribute and display the appropiate DIV upon clicking it. So, here is what the second function looks like:

1
function showViaLink(array)
2
{
3
	array.each(function(i)
4
	{	
5
		$(this).click(function()
6
		{
7
			var target = $(this).attr("href");
8
			$(".container").css("display","none");
9
			$(target).slideDown("slow");
10
		});
11
	});
12
}

Step 7

Now that we have our functions coded, we need to call them appropiately when the page loads. The first thing we need to do is hide all the elements that have class container with the exception of the DIV that has the ID home. Next, we need to call the showViaLink() function with the links inside of our navigation <ul> as its parameter. Last but not least, we have to listen for the user keypress and call the showViaPress() function with the appropiate ID as its parameter. This can be accomplished by using a switch on the key pressed.

The switch will have 5 cases (one for every link) and its number corresponds to the ASCII number for the keypress. For example, if the "a" key is pressed, switch will use case 97. So, here is what the code looks like:

1
$(document).ready(function()
2
{
3
	// hides all DIVs with the CLASS container
4
	// and displays the one with the ID 'home' only
5
	$(".container").css("display","none");
6
	$("#home").css("display","block");
7
	
8
	// makes the navigation work after all containers have bee hidden 
9
	showViaLink($("ul#navigation li a"));
10
	
11
	// listens for any navigation keypress activity
12
	$(document).keypress(function(e)
13
	{
14
		switch(e.which)
15
		{
16
			// user presses the "a"
17
			case 97:	showViaKeypress("#home");
18
						break;	
19
						
20
			// user presses the "s" key
21
			case 115:	showViaKeypress("#about");
22
						break;
23
						
24
			// user presses the "d" key
25
			case 100:	showViaKeypress("#contact");
26
						break;
27
						
28
			// user presses the "f" key
29
			case 102:	showViaKeypress("#awards");
30
						break;
31
						
32
			// user presses the "g" key 
33
			case 103:	showViaKeypress("#links");
34
		}
35
	});
36
});

Step 8

Now that we have all the pieces of the puzzle, we can put it together. Here is what the final iteration of our script should look like:

1
$(document).ready(function()
2
{
3
	// hides all DIVs with the CLASS container
4
	// and displays the one with the ID 'home' only
5
	$(".container").css("display","none");
6
	$("#home").css("display","block");
7
	
8
	// makes the navigation work after all containers have bee hidden 
9
	showViaLink($("ul#navigation li a"));
10
	
11
	// listens for any navigation keypress activity
12
	$(document).keypress(function(e)
13
	{
14
		switch(e.which)
15
		{
16
			// user presses the "a"
17
			case 97:	showViaKeypress("#home");
18
						break;	
19
						
20
			// user presses the "s" key
21
			case 115:	showViaKeypress("#about");
22
						break;
23
						
24
			// user presses the "d" key
25
			case 100:	showViaKeypress("#contact");
26
						break;
27
						
28
			// user presses the "f" key
29
			case 102:	showViaKeypress("#awards");
30
						break;
31
						
32
			// user presses the "g" key 
33
			case 103:	showViaKeypress("#links");
34
		}
35
	});
36
});
37
38
// shows a given element and hides all others
39
function showViaKeypress(element_id)
40
{
41
	$(".container").css("display","none");
42
	$(element_id).slideDown("slow");
43
}
44
45
// shows proper DIV depending on link 'href'
46
function showViaLink(array)
47
{
48
	array.each(function(i)
49
	{	
50
		$(this).click(function()
51
		{
52
			var target = $(this).attr("href");
53
			$(".container").css("display","none");
54
			$(target).slideDown("slow");
55
		});
56
	});
57
}

Demo

Take a look at the script in action on this demo page.
The pattern used in this demo was made by Taylor Satula.

ENDE

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.