Monday, July 18, 2011

Rotating Content

Sorry for the delay in posting the second part of this series. I've been busy with meetings and coding and forgot to post the second and third parts. Here is the second, Rotating content. Again, minimal use of JQuery could be replaced with straight JavavScript to lighten the load times. Simple and clean.

The HTML:
<!--- The Container to rotate through --->
<div id="banner"><a href="#" class="bannerpane">
  <!--- Anything with the class bannerpane inside the banner will be looped through.  It doesn't have to be a link, it could a div containing just about anything. Order of children elements will be order they rotate. --->
  <img src="/letsci/images/pollen_1.png" alt="pollen" title="pollen" class="bannerpane"/>
  </a> <a class="bannerpane" href="/letsci/3"><img src="/letsci/images/starts.png" alt="stars" title="stars" />
</a></div>


The CSS:
/* Use a fixed hight and overflow hidden or at the point it rotates you'll see both stories for a short time.  The other solution is to position the .banner absolutely (which would yield a better transition. */
/* Black background was the best thing to fade to for the images I'm using, if you want to fade to white or another color, set the background here to your color of choice. */
#banner {height:156px;overflow:hidden;background:black;}


The JavaScript:
// To start hide them all except the first,
// you may want to do this with inline style instead of JS,
// in case the user doesn't have JavaScript enabled...  I didn't do that to this, yet.
$('.bannerpane').hide();
$('.bannerpane').first().show();

//function that does the swap.
function rotate() {
  //Basically fade out the current, move it to the bottom, fade in the the new top element.
  // The two 5000's control the length of the fade.  These can be adjusted to taste. 
    $("#banner .bannerpane").first().fadeIn(5000).appendTo('#banner').fadeOut(5000);

    // Recursively call this function again in 7000 microseconds
    // The 7000 can be adjusted to taste.
    setTimeout(rotate, 7000);
}

//Call it the first time.
rotate();

1 comment:

  1. Been reading your blog and this series on Jquery. This is a great aid for website developers.

    ReplyDelete