Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

How To Create A Keypress Navigation Using jQuery

by

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<title>KeyPress Navigation Demo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" type="text/css" href="style.css" />
		<script type="text/javascript" src="jquery.js"></script>
		<script type="text/javascript" src="keypress_nav.js"></script>
	</head>
	<body>
		<div id="header">
			<!-- Our navigation will go here -->
		</div>
		<div id="home">
			<h2>Welcome!</h2>
			<p>Some Text</p>
		</div>
		<div id="about">
			<h2>About Me</h2>
			<p>Some Text</p></p>
		</div>
		<div id="contact">
			<h2>No Spam Please</h2>
			<p>Some Text</p>
		</div>
		<div id="awards">
			<h2>Awards, So Many ...</h2>
			<p>Some Text</p>
		</div>
		<div id="links">
			<h2>Cool Sites</h2>
			<p>Some Text</p>
		</div>
	</body>
</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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<title>KeyPress Navigation Demo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" type="text/css" href="style.css" />
		<script type="text/javascript" src="jquery.js"></script>
		<script type="text/javascript" src="keypress_nav.js"></script>
	</head>
	<body>
		<div id="header">
			<ul id="navigation">
				<li><a href="#home">Home ( a )</a></li>
				<li><a href="#about">About ( s )</a></li>
				<li><a href="#contact">Contact ( d )</a></li>
				<li><a href="#awards">Awards ( f )</a></li>
				<li><a href="#links">Links ( g )</a></li>
			</ul>
		</div>
		<div id="home" class="container">
			<h2>Welcome!</h2>
			<p>Some Text</p>
		</div>
		<div id="about" class="container">
			<h2>About Me</h2>
			<p>Some Text</p></p>
		</div>
		<div id="contact" class="container">
			<h2>No Spam Please</h2>
			<p>Some Text</p>
		</div>
		<div id="awards" class="container">
			<h2>Awards, So Many ...</h2>
			<p>Some Text</p>
		</div>
		<div id="links" class="container">
			<h2>Cool Sites</h2>
			<p>Some Text</p>
		</div>
	</body>
</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:

body 
{
	margin: 0;
	padding: 0;
	font-family: "Lucida Grande", "Lucida Sans", sans-serif;
	font-size: 100%;
	background: #333;
}


/* Header
-------------------------------------------------- */

#header
{
	width: 460px;
	margin: 0 auto;
	font-size: .75em;
	font-family: "Helvetica Neue", Helvetica, sans-serif;
}

#header ul 
{
	list-style: none;
	margin: 0;
	padding: 0;
}

#header ul li 
{
	float: left;
	text-align: left;
}

#header ul li a
{
	display: block;
	color: #ffff66;
	text-decoration: none;
	text-transform: uppercase;
	margin-right: 20px;
}

#header ul li a:hover
{
	text-decoration: underline;
	color: #ffcc66;
}


/* Containers
-------------------------------------------------- */

.container
{
	width: 400px;
	height: 300px;
	margin: 30px auto;
	padding: 10px 20px;
	border: 10px solid #fff;
	color: #fff;
	font-size: .75em;
	line-height: 2em;
}

.container h2
{
	padding: 5px 10px;
	width: 200px;
}

#home		{ background: #15add1; }
#home h2	{ background: #007aa5; }
#about		{ background: #fdc700; }
#about h2	{ background: #bd9200; }
#contact	{ background: #f80083; }
#contact h2	{ background: #af005e; }
#awards		{ background: #f18300; }
#awards	h2	{ background: #bb5f00; }
#links		{ background: #98c313; }
#links h2	{ background: #6f9a00; }


/* Self-Clearing Rules 
-------------------------------------------------- */

ul#navigation:after 
{
    content: ".";
    display: block;
    visibility: hidden;
    clear: both;
    height: 0;
}

* html ul#navigation 	{ height: 1px; }
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:

function showViaKeypress(element_id)
{
	$(".container").css("display","none");
	$(element_id).slideDown("slow");
}

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:

function showViaLink(array)
{
	array.each(function(i)
	{	
		$(this).click(function()
		{
			var target = $(this).attr("href");
			$(".container").css("display","none");
			$(target).slideDown("slow");
		});
	});
}

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:

$(document).ready(function()
{
	// hides all DIVs with the CLASS container
	// and displays the one with the ID 'home' only
	$(".container").css("display","none");
	$("#home").css("display","block");
	
	// makes the navigation work after all containers have bee hidden 
	showViaLink($("ul#navigation li a"));
	
	// listens for any navigation keypress activity
	$(document).keypress(function(e)
	{
		switch(e.which)
		{
			// user presses the "a"
			case 97:	showViaKeypress("#home");
						break;	
						
			// user presses the "s" key
			case 115:	showViaKeypress("#about");
						break;
						
			// user presses the "d" key
			case 100:	showViaKeypress("#contact");
						break;
						
			// user presses the "f" key
			case 102:	showViaKeypress("#awards");
						break;
						
			// user presses the "g" key 
			case 103:	showViaKeypress("#links");
		}
	});
});

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:

$(document).ready(function()
{
	// hides all DIVs with the CLASS container
	// and displays the one with the ID 'home' only
	$(".container").css("display","none");
	$("#home").css("display","block");
	
	// makes the navigation work after all containers have bee hidden 
	showViaLink($("ul#navigation li a"));
	
	// listens for any navigation keypress activity
	$(document).keypress(function(e)
	{
		switch(e.which)
		{
			// user presses the "a"
			case 97:	showViaKeypress("#home");
						break;	
						
			// user presses the "s" key
			case 115:	showViaKeypress("#about");
						break;
						
			// user presses the "d" key
			case 100:	showViaKeypress("#contact");
						break;
						
			// user presses the "f" key
			case 102:	showViaKeypress("#awards");
						break;
						
			// user presses the "g" key 
			case 103:	showViaKeypress("#links");
		}
	});
});

// shows a given element and hides all others
function showViaKeypress(element_id)
{
	$(".container").css("display","none");
	$(element_id).slideDown("slow");
}

// shows proper DIV depending on link 'href'
function showViaLink(array)
{
	array.each(function(i)
	{	
		$(this).click(function()
		{
			var target = $(this).attr("href");
			$(".container").css("display","none");
			$(target).slideDown("slow");
		});
	});
}

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

Advertisement