Need to build smooth and attractive fading techniques into your web site using nothing more than script? This article will explain a proven cross-browser method, with ready-to-use code. If you think you don’t need this, you will conclude otherwise after reading the article!
Cross Fading Navigation with DHTML - Into the Code (Page 3 of 5 )
Ok, so now let’s get into the code, we’ll take it step by step. To start off with, we need to make sure we’re using browsers capable of handling the transitions, and a generic function to find objects.
//========================================= // browser detection var ie5 = ( document.getElementById && document.all ); var moz = ( document.getElementById &&! document.all ); var opera = ( navigator.userAgent.indexOf( 'Opera' ) != -1 ); if ( opera ) ie5 = false;
//========================================= // generic object finder, modify it however you want function getObject( obj ) { var strObj if ( document.all ) { strObj = document.all.item( obj ); } else if ( document.getElementById ) { strObj = document.getElementById( obj ); } return strObj; }
Both Internet Explorer and Mozilla are good browser candidates. Opera however, will try to qualify at first pass by meeting the IE5 requirements. Therefore we have to do some string checking, and make sure Opera is identified correctly. For this browser and other non-DHTML friendly browsers, the menus will just pop in and out of existence, without fading.
Visual Manipulation
Now let’s get into the actual visual manipulation. The most efficient route to take, is to fade out the entire navRowSpan, make sure all sub-items are not displayed, display only the desired sub-items, then fade the whole navRowSpan back in. To do this, it’s best to use two functions: one to handle swapping the displayed items, one for the fading.
Let’s start with the first function, and declare the global variables that will be shared between the two:
//======================================= // instantiate global variables var wait, goIn, intRightNow, inUse;
// first function, swaps the active sub items function swapNav( intNavSpan ) {
The first thing we need to do is prevent the swapping of the same items simultaneously, or even trying to fade in an object that’s already active (full opacity).
But what happens if a user moves their mouse over another item in the middle of the fade? The best way to handle it is to stop fading in, fade it out quickly, and start on the new one.
Here’s where we make the call to fade the whole thing out.
We wait until that process is finished, and then loop through the sub items, and make sure they’re all hidden. For efficiency’s sake, we define the maxInt, the total number of sub item containers, so that we can quickly locate them all.
NOTEThe items do not start with an index of ‘0’ in my example, so maxInt truly reflects the total.