View
Download
We will be taking your average everyday website and enhancing it with
jQuery. We will be adding ajax functionality so that the content loads
into the relevant container instead of the user having to navigate to
another page. We will also be integrating some awesome animation effects
Step 1
First thing’s first, go and download the latest stable release of
jQuery and link to it in your document:
<script type="text/javascript" src="jQuery.js"></script> |
One of the best things, in my opinion, about jQuery is it’s simplicity.
We can achieve the functionality described above coupled with stunning
effects in only a few lines of code.
First let’s load the jQuery library and initiate a function when the document is ready (when the DOM is loaded).
$(document).ready(function() { |
Step 2
So what we want to do is make it so that when a user clicks on a link
within the navigation menu on our page the browser does not navigate to
the corresponding page, but instead loads the content of that page
within the current page.
We want to target the links within the navigation menu and run a function when they are clicked:
$('#nav li a').click(function(){ |
Let’s summarize what we want this function to do in event order:
-
Remove current page content.
-
Get new page content and append to content DIV.
We need to define what page to get the data from when a link is clicked
on. All we have to do here is obtain the ‘href’ attribute of the
clicked link and define that as the page to call the data from, plus we
need to define whereabouts on the requested page to pull the data from –
i.e. We don’t want to pull ALL the data, just the data within the
‘content’ div, so:
var toLoad = $(this).attr('href')+' #content'; |
To illustrate what the above code does let’s imagine the user clicks on
the ‘about’ link which links to ‘about.html’ – in this situation this
variable would be: ‘about.html #content’ – this is the variable which
we’ll request in the ajax call. First though, we need to create a nice
effect for the current page content. Instead of making it just disappear
we’re going to use jQuery’s ‘hide’ function like this:
$('#content').hide('fast',loadContent); |
Step 3
Once the old content disappears with an awesome effect, we don’t want
to just leave the user wondering before the new content arrives
(especially if they have a slow internet connection) so we’ll create a
little “loading” graphic so they know something is happening in the
background:
$('#wrapper').append('<span id="load">LOADING...</span>'); |
$('#load').fadeIn('normal'); |
Here is the CSS applied to the newly created #load div:
background: url(images/ajax-loader.gif); |
}
No comments:
Post a Comment