Load in and Animate content with JQuery

I found out how to load and animate content using this excellent tutorial from tutsplus.com. But I wanted to take it one step further and also show the currently active link highlighted in the menu bar which took a bit of effort.

The full working sample can be downloaded from here.

Here’s the final version of the javascript:

$(document).ready(function(){

var hash = window.location.hash.substr(1);
var href = $(‘#nav li a’).each(function(){
var href = $(this).attr(‘href’);
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+’.html #content’;
$(‘#content’).load(toLoad)
}
});

$(“.nav li a”).click(function(e){

var toLoad = $(this).attr(‘href’)+’ #content’;

var clickedMenuItem = $(this);//Store whatever you clicked over here

var currentMenuItem = $(this);//This is where you’ll store whatever is currently selected (in the next step)

$(“.nav li a”).each(function(){
if($(this).hasClass(“active”)){
currentMenuItem = $(this);//If it is active then set that to the currentMenuItem
return false;//Break out of the each() loop (http://gavinroy.com/jquery-tip-how-to-break-out-of-each)
}
return true;//Just to get rid of the warning “Function doesn’t always return a value”
});
e.preventDefault();
//Change animations to slideUp and slideDown to get the sliding animation
$(“#content”).fadeOut(‘slow’,function(){
$(“#content”).load(toLoad, function(){
$(“#content”).fadeIn(‘slow’);
});
});

window.location.hash = $(this).attr(‘href’).substr(0,$(this).attr(‘href’).length-5);
currentMenuItem.removeClass(“active”);//First remove and then add in case the same link is clicked
clickedMenuItem.addClass(“active”);

});

});

Advertisements

2 thoughts on “Load in and Animate content with JQuery

  1. Hi,

    thank you for your grate completing this example. I have a question and i want to ask,
    I am going to use “tinyscrollbar”, “Fancybox” on this example but after you change some pages it seams Javascript does not working anymore, I was googleing this problem but I couldnt find any proper answer, would you please help me out?

    regards

    • Not sure what the issue might be. Is the problem showing up in different browsers as well? Maybe there is some issue with the way you are linking to the different pages. For example, when you click and go to “About.html”, maybe it is not configured in the same way as “Index.html”.

      It’s been a while since I’ve worked on jQuery, so I’m not sure if I can help you more with this. Would suggest you try one of the forums or mailing lists.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s