Search code examples
javascriptjqueryscrollfadeparallax

How can I tidy up this short javascript code?


jsfiddle: http://jsfiddle.net/s1d368ce/

I am trying to get three separate headers (h1, h2, and h3) to fade out when the user scrolls down the page. I want each header to fade out slightly slower than the one above, so I have three parts to my code, as follows. However, only the last bit works (i.e. the h3 fades out but h2 and h1 don't. If I remove the last section for h3, then h2 fades out but h1 does not. And if I remove the h3 and h2 javascript then h1 fades out.)

I wonder if anyone could show me how to re-organize the code so that it works?

Please see my code demo; only the code for h3 works. But, if I were to remove the 'scroll-fade-long-2' section of the javascript code, then h2 would fade out, but not h1. ??

Thank you so much!

jQuery(function($){		
//Scroll fade
		var divs = $('.scroll-fade');
		$(window).on('scroll', function() {
			var st = $(this).scrollTop();
			divs.css({ 
				'margin-top' : -(st/3)+"px", 
				'opacity' : 1 - st/135
        		}); 
		});
		
		//Scroll fade long
		var divs = $('.scroll-fade-long');
		$(window).on('scroll', function() {
			var st = $(this).scrollTop();
			divs.css({ 
				'margin-top' : -(st/3)+"px", 
				'opacity' : 1 - st/255
			}); 
		});


		//Scroll fade long2
		var divs = $('.scroll-fade-long-2');
		$(window).on('scroll', function() {
			var st = $(this).scrollTop();
			divs.css({ 
				'margin-top' : -(st/3)+"px", 
				'opacity' : 1 - st/355
			}); 
		});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="scroll-fade">header 1</h1>
<h2 class="scroll-fade-long">header 2</h2>
<h3 class="scroll-fade-long-2">header 3</h3>



<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


Solution

  • My demo EDIT: updated the opacity. Did a quick copy paste. Works.

    You only need to call the $(window).on('scroll', function(){}); once.

    var sf = $('.scroll-fade');
    var sfl = $('.scroll-fade-long');
    var sfl2 = $('.scroll-fade-long-2');
    
    $(window).on('scroll', function(){
        var st = $(this).scrollTop();
        sf.css({
            'opacity' : 1 - st/135,
            'margin-top': -(st/3)+"px"
        });
        sfl.css({
            'opacity' : 1 - st/255,
            'margin-top': -(st/3)+"px"
        });
        sfl2.css({
            'opacity' : 1 - st/355,
            'margin-top': -(st/3)+"px"
        });
    });
    

    Also see Miro's compact solution: http://jsfiddle.net/ocntm9tx/5/

    $(window).on('scroll', function(){
        var st = $(this).scrollTop();
        for(i=1; i<=3; i++){
            $('.scroll-fade-'+i).css({
                'opacity' : 1 - st/(i*100),
                'margin-top': -(st/3)+"px"
            });
        }
    });