Proper jQuery Cross-Fading


/ Published in: JavaScript
Save to your folder(s)

Looked for a simple, efficient cross-fading script that does it properly without fading to the background color. This script uses z-indexes to prevent the background from ever showing, creating a smooth fade.


Copy this code and paste it in your HTML
  1. //Switch background image
  2. function bgswitch() {
  3. $("#homeBackground li:first").css("z-index","3"); //Using z-index's to get a proper cross-fade
  4.  
  5. $("#selector li").click(function(){
  6.  
  7. if ($(':animated').length > 0) { //wait until animation is complete
  8. return false;
  9. } else {
  10.  
  11. if ($(this).attr("class") != "active" ) {
  12. var index = $("#selector li").index(this);
  13.  
  14. $("#homeBackground li:eq("+ index +")").css("z-index","2");
  15. $("#homeBackground li:eq("+ index +")").show();
  16. /*if($.browser.msie){
  17. $("#sections div.active").removeClass("active");
  18. } else { */
  19. $("#sections div.active").fadeOut("slow", function(){
  20. $("#sections div:eq("+ index +")").fadeIn(1050);
  21. $(this).removeClass("active");
  22. $("#sections div:eq("+ index +")").addClass("active");
  23. });
  24. /*}*/
  25.  
  26. $("#homeBackground li.active").fadeOut("slow", function(){
  27. $(this).css("z-index","1");
  28. $("#homeBackground li:eq("+ index +")").css("z-index","3");
  29.  
  30. $(this).removeClass("active");
  31. $("#homeBackground li:eq("+ index +")").addClass("active");
  32.  
  33. /*if($.browser.msie){ $("#sections div:eq("+ index +")").addClass("active"); }*/
  34.  
  35. });
  36.  
  37. //$("#homeBackground li.active").fadeOut("slow");
  38. //$("#homeBackground li:eq("+ index +")").fadeIn("slow");
  39.  
  40. $("#selector li").removeClass("active");
  41. $(this).addClass("active");
  42. }
  43. return false;
  44. }
  45. });
  46. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.