Learning jQuery: Fading Menu – Replacing Content

Update January 2013: Best practice for this kind of this is detailed here.

Update May 2010: I'm considering this article deprecated. I have an updated article here, which covers this same type of material only with more features, updated technology, and better practices.

The more I learn about jQuery, the more natural it feels. Probably because of how closely tied to CSS it is. From a design perspective, the syntax for jQuery is:

"When I do this, make the CSS do this."

The more common slogan is:

Find something, do something.

...which is also awesome.

So now instead of thinking about CSS as page layout and a way to style your page when it loads, you can use in animation and change it on-the-fly to react to events that happen on your page. Take for example a menu. You can take the "click" event that happens when clicking on a menu to do lots of stuff.

This example page has three menu items and three content areas: home, about, and contact. By default, the home button is selected, meaning that it's menu graphic is at full opacity and it's content area is shown:

Your complete javascript code would have similar chunks for all three buttons. As I've mentioned before, I'm just learning here, so there is likely to be a way smarter way of writing this, but these are the basics and they work.

UPDATE: This is way smarter.

$("#page-wrap div.button").click(function(){
$clicked = $(this);
// if the button is not already "transformed" AND is not animated
if ($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) {
$clicked.animate({
opacity: 1,
borderWidth: 5
}, 600 );
// each button div MUST have a "xx-button" and the target div must have an id "xx"
var idToLoad = $clicked.attr("id").split('-');
//we search trough the content for the visible div and we fade it out
$("#content").find("div:visible").fadeOut("fast", function(){
//once the fade out is completed, we start to fade in the right div
$(this).parent().find("#"+idToLoad[0]).fadeIn();
})
}
//we reset the other buttons to default style
$clicked.siblings(".button").animate({
opacity: 0.5,
borderWidth: 1
}, 600 );
});

Anyone know how to fade in a background image on MouseOver on a LI element, and obviously fade out the background on MouseOut? I’ve been searching for jQuery code, and all I found was one that dealt with color only.

good work!
i am looking for a fade for dynamic content. i mean, i am loading external content from external serverside file in a div and this loading should be fading when loading. is there any work like what i want?

Love what you have done here great job and thanks for sharing. One thing though, I am new to this and I was wondering when I put a div (Nivo Slider) inside of the div id=”home” on page load it shows the content but when i click div id=”about” then back to the home tab it does not show the content. How can I fix this?