Ricardo Patrick
Ricardo Patrick

Reputation: 81

opacity on scroll with jquery

I'm trying make the opacity of my div gradually increasing, as will moving the scroll, like this

$(document).ready(function() {
    $(document).scroll(function(e) {
        opacidade();
    });

    var element = $('#element');
    var elementHeight = element.outerHeight();

    function opacidade() {
        var opacityPercent = window.scrollY / 100;
        if (scrollPercent <= 1) {
            element.css('opacity', opacityPercent);
        }
    }
});

is working but the opacity is uping very fast i find example decrease opacity but no uping upacity if in my rule css my div is declared opacity 0 any knwo how should be

Upvotes: 0

Views: 519

Answers (1)

fuyushimoya
fuyushimoya

Reputation: 9813

Altered: jsFiddle

$(document).ready(function() {
    $(document).scroll(function(e){
        opacidade();
    });

    var element = $('#element');
    var elementHeight = element.outerHeight();

    function opacidade(){
        var opacityPercent = window.scrollY   / $(document).height();
        console.log(window.scrollY, opacityPercent);
            element.css('opacity', opacityPercent);
    }
});
  1. The scrollY is a pixel value, so unless you limit your possible scroll range [0 - 100], there's no reason to divide it by 100.
  2. So what you need is divide the scroll by the total document's height (or whatever it's parent that contains it and display a scrollbar)

Upvotes: 1

Related Questions