Here’s a useful trick for fading similar elements sequencially without having to chain the effects. In the first example I have 5 divs that I want to fade in one after the other. Instead of giving them all unique ID’s and chaining the fade effects like this….
$("#box1").fadeIn("slow", function(){$("#box2").fadeIn("slow", function(){$("#box3").fadeIn("slow", function(){$("#box4").fadeIn("slow", function(){$("#box5").fadeIn("slow");});});});});
…… you can instead give them a class of ‘box’ and find the amount using .length; and use an if statement to loop through the until all the relevant elements are visible using a callback function.
var i = 0var n = $(".box").length;function showbox() {if(i <= n){$(".box").eq(i).fadeIn(600, function(){ i++; showbox(); });}} showbox();
It’s a lot more efficient code wise and produces the same effect. Here’s the same thing but using a ‘click’ event to trigger the function.
var j = 0var a = $(".list").length;$("#trigger").click(function showlist(){if(j <= a){$(".list").eq(j).fadeIn(200, function(){ j++; showlist(); });}});
Might be a nice effect for a menu? I was going to use it to fade in the posts on the blog homepage but IE7 can’t render one transparent PNG over another when faded. It comes out looking like a jaged GIF with the top PNG’s transparent pixel looking black instead. Once again IE ruins everything!!!
If you liked my post then,
Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!
0 comments: on "JQuery: Fade elements sequencially without chaining"
Post a Comment