Geoff
Geoff

Reputation: 199

jQuery opacity slow fade

I have a screen div overlay on top of a supersized banner set. From the start the overlay needs to be set to 0.5 opacity, then when the user starts scrolling over a period of about 300px scroll it fade gently to 0.9 opacity then stops at that, if the user scrolls back up to less than 300px from top then it starts to fade slowly back to 0.5 opacity. I'm just using a background color on the div for this.

I'm a little stuck though. I have the below so far but as you start scrolling it goes to 0 opacity then starts from that and fade to 0.9, then at 300px it goes to 1 opacity then after 301px if jumps back to 0.9 opacity.

$(function () {
    divFade = $(".fadeScreen");
    var toggleHeader = function (noAnimate) {

        var threshold  = 1,
            fadeLength = 300,
            opacity,
            scrollTop  = $(document).scrollTop();

        if (scrollTop < threshold) {
            opacity = 0.5;
        } else if (scrollTop > threshold + fadeLength) {
            opacity = 0.9;
        } else {
            if (noAnimate) {
                opacity = 0.9;
            } else {
                opacity = (scrollTop - threshold) / fadeLength;
            }
        }
        divFade.css("opacity", opacity);
    };

    toggleHeader(true);
    $(window).scroll(function () {toggleHeader();});
});

I just need it so when the page is loaded the opacity is 0.5, between 0-300px scrolling it changes slowly to 0.9 and stays, then when scrolling back up it fades back to 0.5 opacity.

Thanks for any help.

Upvotes: 0

Views: 188

Answers (1)

daymosik
daymosik

Reputation: 140

How about this

$(function() {
  divFade = $(".fadeScreen");
  var toggleHeader = function(noAnimate) {

    var threshold = 1,
      fadeLength = 300,
      minOpacity = 0.5,
      maxOpacity = 0.9,
      opacity = minOpacity,
      opacityDiff = (maxOpacity - minOpacity),
      scrollTop = $(document).scrollTop();

    if (scrollTop < fadeLength) {
      opacity += (scrollTop / fadeLength) * opacityDiff;
    } else {
      opacity = maxOpacity;
    }
    console.log(scrollTop);
    divFade.css("opacity", opacity);
  };

  toggleHeader(true);
  $(window).scroll(function() {
    toggleHeader();
  });
});

Upvotes: 1

Related Questions