Designing simple navigation using jQuery
jQuery is a development framework that allows us to use JavaScript in our HTML document. Now we will build a simple navigation using the basic jQuery features.
Before we can begin, we need to include the latest jQuery library. We can download it from the download section at www.jquery.com. We will save it in our JavaScript folder named js
, in the root of our HTML document, for example, cookbook
.
All libraries mentioned in this book are also available in an online cache such as http://code.google.com/apis/libraries/
.
Now, we can start coding our task1
.html
page. We'll place it in the cookbook
folder.
Now, let's explain what we have done in the preceding code snippet. The main idea of our script is to find each hyperlink <a>
in the document, prevent its default functionality, and display the hyperlink content in our placeHolder
. From the beginning, we started with doctype
and the main HTML layout. The body of the page contains a navigation
and a placeholder
element for the dynamic content.
The most important part for jQuery functionality is to include our jQuery library. Let's place it before the closing <body>
tag. This will allow the HTML of a page to load first:
After loading our HTML page and when the document is ready, we can define our JavaScripts scripts in the $(document).ready()
function:
This can be also shortened to $()
:
The dollar sign $()
represents an alias to the jQuery()
factory
function. Within this function we can use all the CSS selectors like ID, class, or exact tag names. For example:
$('a')
: Selects all hyperlinks in our document
$('#myID')
: Selects the element with this ID
$('.myID')
: Selects all elements with this class
In our case, we are selecting all hyperlinks in the navigation <div>
and defining their own functionality with an event handler for click
events:
And the last step of our example is creating the title
VAR and HTML string, which goes to the placeHolder
:
The preceding example was really simple. But there is a lot more that jQuery can offer to us. This includes special selectors, effects, DOM manipulation, or AJAX functionality.
We can specify our selectors more precisely. For example, we can specify which hyperlinks should be affected based on their href
attributes:
jQuery also covers all possible events (click
, blur
, focus
, dblclick
, and so on), visual effects (hide
, show
, toggle
, fadeIn
, fadeOut
, and so on), or DOM manipulations (appendTo
, prependTo
, and so on). It has a full suite of AJAX capabilities, which are really easy to use, such as:
But we will have a better look at more jQuery features in further tasks and chapters.