martincarstens
12/20/2016 - 9:26 PM

Trigger and control element opacity while scrolling

Trigger and control element opacity while scrolling

    <script type="text/javascript">
        $(document).ready(function() {
            $(function () {

                function setVars(el, divFade) {

                    thresholdIn  = ($(el).offset().top + $(el).outerHeight());
                    thresholdOut  = thresholdIn + (($(window).height() - $(el).outerHeight()) / 2) + ($(el).outerHeight() / 2);       
                    fadeLength = (($(window).height() - $(el).outerHeight()) / 2);

                    return  {   
                                'el': el,
                                'divFade': divFade,
                                'thresholdIn': thresholdIn,
                                'thresholdOut': thresholdOut,
                                'fadeLength': fadeLength
                            }
                }

                function manualPulse(wp, scrollBottom) {

                    if (scrollBottom < wp.thresholdIn) {
                        opacity = 0;
                    } else if (scrollBottom > wp.thresholdIn + wp.fadeLength) {
                        opacity = 1;
                    } else {
                         opacity = (scrollBottom - wp.thresholdIn) / wp.fadeLength;
                    }

                    if (scrollBottom > wp.thresholdOut) {
                        if (scrollBottom > wp.thresholdOut + wp.fadeLength) {
                            opacity = 0;
                        } else {
                            opacity = 1 - (scrollBottom - wp.thresholdOut) / wp.fadeLength;
                        }                 
                    }

                    wp.divFade.css("opacity", opacity);

                    /*console.log('thresholdIn: ' + wp.thresholdIn);
                    console.log('fadeLength: ' + wp.fadeLength);
                    console.log('scrollBottom: ' + scrollBottom);
                    console.log('opacity: ' + opacity);
                    console.log('thresholdOut: ' + wp.thresholdOut);*/
                }

                wp_1 = setVars("#waypoint1",$("#fadeMe"));
                wp_2 = setVars("#services",$("#fadeMe2"));                 

                $(window).scroll(function () {
                    scrollBottom = $(window).scrollTop() + $(window).height();
                    manualPulse(wp_1,scrollBottom);
                    manualPulse(wp_2,scrollBottom);
                });

            });
        });


    </script>