jQuery fade out elements as they scroll off page, fade back as they scroll back on -
i want elements fade out scroll off top of page, , fade in scroll onto page. wrote code works, looking more elegant solution. here solution have working on jsfiddle: http://jsfiddle.net/wmmead/jdbhv/3/
i find shorter, more elegant piece of code, can't quite work out. maybe array , each() method? if put class on divs instead of id, gets lot shorter, fade out @ once. want each box fade out scrolls off page.
html
<div id="box1"></div> <div id="box2"></div> <div id="box3"></div> <div id="box4"></div> <div id="box5"></div> <div id="box6"></div>
css
#box1, #box2, #box3, #box4, #box5, #box6 { width: 100px; height: 100px; background: orange; margin:100px auto; } #box6 { margin-bottom:600px; }
jquery
var box1top = $('#box1').offset().top; var box2top = $('#box2').offset().top; var box3top = $('#box3').offset().top; var box4top = $('#box4').offset().top; var box5top = $('#box5').offset().top; var box6top = $('#box6').offset().top; $(window).scroll(function () { if ((box1top - $(window).scrolltop()) < 20) { $('#box1').stop().fadeto(100, 0); } else { $('#box1').stop().fadeto('fast', 1); } if ((box2top - $(window).scrolltop()) < 20) { $('#box2').stop().fadeto(100, 0); } else { $('#box2').stop().fadeto('fast', 1); } if ((box3top - $(window).scrolltop()) < 20) { $('#box3').stop().fadeto(100, 0); } else { $('#box3').stop().fadeto('fast', 1); } if ((box4top - $(window).scrolltop()) < 20) { $('#box4').stop().fadeto(100, 0); } else { $('#box4').stop().fadeto('fast', 1); } if ((box5top - $(window).scrolltop()) < 20) { $('#box5').stop().fadeto(100, 0); } else { $('#box5').stop().fadeto('fast', 1); } if ((box6top - $(window).scrolltop()) < 20) { $('#box6').stop().fadeto(100, 0); } else { $('#box6').stop().fadeto('fast', 1); } });
you can use attribute selector '[attr="someattr"]'
use of .each()
method of jquery:
$(window).scroll(function () { $('[id^="box"]').each(function () { // <---loop divs id starts #box if (($(this).offset().top - $(window).scrolltop()) < 20) { //<---mark $(this).offset().top of current object $(this).stop().fadeto(100, 0); //<----fadeout current obj } else { $(this).stop().fadeto('fast', 1); //<----fadein current obj } }); });
you can take demo here:
Comments
Post a Comment