The VariablesThere are no arrays or complex variables within this project. Instead we have five simple variables that track the various aspects of the rotator. First, we need to define the boundaries for the rotator. The contentAreas variable defines the number of content areas that we have to rotate through and the changeDelay variable defines the delay (in milliseconds) between changes of content.
The other three variables are used to track the state of the content rotator. The contentIndex variable keeps track of which content area is currently being displayed. The continueRotation variable is a flag that tells us when content rotation is on and off. The rotationInProgress variable keeps track of when we are within the delay window after setTimeout is used and before the rotateContent function is actually executed. You'll see why this is necessary below.
Function - rotateContentThis function handles the actual rotation of the content. The best way to explain how this function works is to walk through it step by step:
- We first check to see if the rotation is currently on or off using the continueRotation flag.
- If we are continuing rotation we do the following:
- Turn off the current content area using the contentIndex variable to figure out what content area to turn off. The display style is set to none which renders the content area invisible.
- Change the index value to the next content area or roll back to the beginning if we have reached the end.
- Use the new index value to turn on the appropriate content area by setting the display style for the content area to inline.
- The function continues the rotation by calling itself using setTimeout to delay the execution by the number of milliseconds that is defined in the changeDelay variable.
- Ensure the rotationInProgress flag that tracks when we are in the middle of a rotation delay is set to on (1).
- If we are not continuing the rotation we simply reset the rotationInProgress flag to off (0) as we are no longer rotating therefore we are not within the delay period.
Tip: This technique works with other elements like div, although I prefer to always use tables and cells so that I can have my rotating content in a nicely aligned and framed area of my page.