Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use throttle from underscore.js

I want to use throttle from underscore.js but I don't know how to implement it in my code.

<script type="text/javascript"> 
    $(document).ready(function() {
        /* Scroll event handler */
        $(window).bind('scroll',function(e){
            parallaxScroll();
        });
    }); 

    /* Scroll the background layers */
    function parallaxScroll(){
        var scrolled = $(window).scrollTop();
        $('header').css('top',(0+(scrolled*1))+'px');
        $('#balken0').css('top',(-600+(scrolled*1))+'px');
        $('#balken1').css('top',(-1465+(scrolled*1))+'px');
        $('#balken2').css('top',(-2320+(scrolled*1))+'px');
    }
</script>

Thank you in advance!

like image 763
Just Kidding Avatar asked Nov 25 '25 18:11

Just Kidding


1 Answers

You can achieve the same result by using a timer. There's no point including an entire library for one function IMO.

Try this:

$(document).ready(function() {
    var timer;

    /* Scroll event handler */
    $(window).bind('scroll', function(e) {
        clearTimeout(timer);
        timer = setTimeout(parallaxScroll, 100);
    });
}); 

This will ensure that the scroll event only fires your parralax function after scrolling has ended, instead of calling it once for every pixel the page is scrolled by.

like image 132
Rory McCrossan Avatar answered Nov 27 '25 06:11

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!