Creating a navigation menu with CSS & jQuery

Created by Martin Angelov on Jul 31st, 2009

ZineScripts.com

Introduction

As you remember, we already created the navigation graphics in Photoshop and exported them using the slice tool. Now we use them to create our navigation menu, at the top of the page. You can view a working example at BloggyBits.com.

The navigation bar

The navigation bar

Including the files

We are using Adobe Dreamweaver as our development  environment. We are also using the jQuery framework and the scrollTo plugin, which make possible for a smooth page scrolling effect.

The first thing, we need to do is include these into our site’s index.php. As you may remember, we used this code in the head section:

<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript"
src="/jquery-ui/jquery.scrollTo-min.js"></script>

We firstly include the jQuery library itself, and later the scrollTo plug-in. Those files are compressed, so they load as fast as possible.

The XHTML

Now we have to create the XHTML structure  of the menu. We are using a regular anchor elements, positioned inside a DIV with id=”topBar“. We are using this id later to add CSS styles to the links.

<div id="topBar">
<a href="#choose" class="choose replaceLink">choose</a>
<a href="#configure" class="configure replaceLink">configure</a>
<a href="#generate" class="generate replaceLink">generate</a>

<!-- AddThis Button BEGIN -->
<a href="http://www.addthis.com/bookmark.php?v=250&pub=xa-4a4a1d364dccfa82" onmouseover="return addthis_open(this, '', '[URL]', '[TITLE]')" onmouseout="addthis_close()" onclick="return addthis_sendto()" class="share">share</a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a4a1d364dccfa82"></script>
<!-- AddThis Button END -->

</div>

Below our three links, there is the AddThis button, but with changed default image, as you can see below.

The CSS

The anchor elements share the replaceLink class, which is only used to be select with jQuery, which I will demonstrate later. They also each have a respective class, that contains unique style properties, as shown below.

.choose{
	width:100px;
	height:22px;
	background-image:url(/images/steps/1.gif);
}

.configure{
	width:114px;
	height:22px;
	background-image:url(/images/steps/2.gif);
}

.generate{
	width:110px;
	height:22px;
	background-image:url(/images/steps/3.gif);
}

.share{
	margin-left:288px;
	width:155px;
	height:22px;
	background-image:url(/images/steps/share.gif);
}

#topBar{
	margin:25px 0px 30px 0px;
	width:100%;
	height:22px;
	background-color:#2b2b2b;
	border:1px solid #363636;
	overflow:hidden;
}

#topBar a{
	float:left;
	display:block;
	text-indent:-400px;
	overflow:hidden;
	background-position:top;
}

#topBar a:hover{
	background-position:bottom;
}

As you see, every one of the unique CSS classes has width and height property, as well the images, we created before, as backgrounds. At the bottom are the #topBar styles. This is where the magic happens. #topBar a (line 35) is a CSS selector, that is valid for all the hyperlinks in the DIV with an ID of topBar. That means, that the rules it specifies, affect those same hyperlinks, which we use as navigation.

On line 36 you see that the links get floated to the left and we use the same trick as we used in the heading last time – using text-indent with a negative value we hide the text and the only thing that is left is the background. That way you have a regular hyperlink for the search engines, and a graphical button for the users with browsers that support CSS.

There is also one important reason to use hyperlinks with text indented to the side – hyperlinks (anchors) are the only elements that have a hover CSS property that is supported on all used browsers today. This is illustrated on line 43.

As you remember, we created the images for the buttons with their normal state at the top part of the image, and the hover state right below.

So suddenly lines 40 and 44 make sense – the anchor elements in their normal state show the top part of the image (thanks to the background-position property) and once you move you mouse above them, they show the bottom part.

The jQuery magic

But what is looks without functionality? Currently, the links display the same behavior as any other link. We need to make the transition stylish. Here come all the possibilities provided by the jQuery javascript library and it’s handy plug-ins.

We already included the needed files, but how do we create that smooth scroll effect you can observe on the site?

The scrollTo plugin gives us the ability to call a special javascript method, that scrolls the page we are viewing.

$(document).ready(function() {
$('#topBar .replaceLink').attr('onclick',
'$.scrollTo(this.hash,800);return false;');
}

This might look slightly from outer space so I am going to explain it. Line 1 is binding the function we provide, with the onload event of the document. In other words it gets executed only after the page is fully loaded.

Now lets look inside the anonymous function – function() {….}. The dollar sign acts as a special function, that calls jQuery methods to extend the specified elements in the brackets. In this case, we have specified a CSS selector – ‘#topBar .replaceLink’,  which practically means “Select all elements within the one with ID of topBar which have been assigned a class name of replaceLink“. Those are actually our three navigation buttons.

For each of those buttons the method ‘attr’ is executed, which sets the onclick property to ‘$.scrollTo(this.hash,800); return false;‘. What this does is scrolls the page after we click the link and later returns false, in order to prevent the default action which would ruin the smooth scroll effect.

An alternative to this would be to bind an Event listener to the click event (should also be put inside the $(document).ready):

$('#topBar .replaceLink').click(function(event){
    event.preventDefault();
    $.scrollTo(this.hash,800);
}

This second version uses event.preventDefault(); to stop the link from redirecting the page, once clicked.

Now lets say a few words about the scrollTo function. It takes two parameters, the first is where to scroll the page to, and the second is the duration of the scroll in milliseconds.

In the above examples we use $.scrollTo(this.hash,800); which takes the hash part of the hyperlink we are currently working with (this.hash corresponds to ‘#choose’,'#configure’ or ‘#generate’ respectively) and feeding it to the function as a parameter.

Conclusion

Today we built upon the techniques we learned in the previous tutorials and created a CSS and jQuery based smooth scrolling navigation menu. I explained the basics of the jQuery selectors and some of the methods.

Next time we write our first PHP code and use jQuery to create the configuration section that allows you to select services on the BloggyBits website.

Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

5 Responses

  1. Avangelist says:

    I like what you are trying to teach, but I cannot follow this for love nor money. You can clearly do the work but your explanations are not doing it for me. I am trying ever so hard, but there is just insufficient information somewhere along the line because following this from start to finish (including the sliced image section) I have got a grey navbar with no buttons.

  2. Avangelist says:

    Actually I take that all back. I had to read through a few times but I now understand it.

  3. Martin Angelov says:

    @Avangelist
    Hello and thank you for your comment. Unfortunately there is no way to present how a site is created from start to finish in a single resource. That is why the information is divided between tutorials that are posted regularly.
    There are already several tutorials published that precede this one, and to be able to fully comprehend the techniques used here, you’d need to take a glimpse at the older ones.
    I try to link to relevant tutorials that have been published already, so that I ease the reader as much as I can, but as it seems there are still some blind spots. I will take great care to ensure that this doesn’t happen with the future articles.

  4. ticicic says:

    oh! thank you soooooooooooooooo much! I tried soooo hard to find out what do I have to put in my document-ready(function(:))))))) cause im not so familiar with jq:)
    I have looked into many tutorials but only yours got great explained example!
    thank you

  5. This is great, pretty clear and straight forward. I don’t know JQ or any other scripting language but always wanted to know the finer bits of code and what they do – which is what you are showing, so, thank you!

Leave a Reply

Some HTML Tags are OK, Use Entities For The Rest