I've wrote a little jQuery plugin to start decreasing the opacity of a section when said section reaches the top of the window.

Now I wanna add an offset to that starting point, namely I wanna start decreasing the opacity when the element is half of its height away from the top of the window.

I've created a pen here: https://codepen.io/cosminn/pen/bywpOe

And you can also view the code below:

(function ( $ ) {
    $.fn.hideScroll = function() {
        return this.each(function(){ //Required for inidivudal elements of the same type
            var elem = $(this),
                elementTop = elem.offset().top,
                elementHeight = elem.outerHeight(),
                opacity, scale;
            $(document).bind('scroll', function(){
                var areaHidden = $(window).scrollTop() - elementTop, // How much of the element is off-screen at the top
                    areaVisible = elementHeight - areaHidden,
                    limit = $(window).scrollTop() + (elementHeight / 2);
                if (elementTop <= limit) {
                    opacity = areaVisible / elementHeight; // Equivalent to how much percent of the element is visible
                else opacity = 1; // Sometimes the opacity remains at 0.9XXX, so we turn it to 1 when element is in-view or off-screen at the bottom of window
                elem.css('opacity', opacity);
}( jQuery ));


My problem is here:

limit = $(window).scrollTop() + (elementHeight / 2);
if (elementTop <= limit)

It feels like whatever is added in the limit variable after $(window).scrollTop() is ignored.

I'm not really a developer, so there might be an obvious thing I'm missing.

1 Answers

skobaljic On Best Solutions

Just imagine the element starts further down and is half height, which means:

var elementHeight = elem.outerHeight()/2;
var elementTop = elem.offset().top + elementHeight;

Your New Pen.