dungey_140
dungey_140

Reputation: 2802

Jquery transition Opacity based on var value

I am trying to animate an opacity value from 0 to 1, based on the scroll position within the viewport height. The code below sets variables for windowHeight and scrollTop, which can be combined to calculate percentageScrolled (0–100) of the viewport height. Based on this I am able to switch CSS values at set points, but instead I want to gradually change the opacity from 0–100 of percentageScrolled.

How can I adjust the code below to transition/animate the opacity?

Thanks.

$(window).on('scroll', function(){

    // Vars
    var windowHeight = $(window).height();
    var scrollTop = $(this).scrollTop();
    var percentageScrolled = (scrollTop*100)/windowHeight;

    if( percentageScrolled < 100 ) {
        $('.colour-overlay').css('opacity', '1');
    } else {
        $('.colour-overlay').css('opacity', '0');
    }

});

Upvotes: 0

Views: 170

Answers (3)

Alen.Toma
Alen.Toma

Reputation: 4870

Dont know if i understood you right, but a wrote an example have a look.

$(document).on('scroll', function(){

    // Vars
  // use body instead of window, body will return the right height where window will return the view size
    var windowHeight = $("body").height(); 
    var scrollTop = $(this).scrollTop();
var percentageScrolled = Math.abs((((scrollTop / windowHeight) * 100) / 100 ));
  $('.colour-overlay').css('opacity', percentageScrolled);

});
.colour-overlay{
background:red;
height:1000px;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colour-overlay"></div>

Upvotes: 1

$(‘.colour-overlay’).css(opacity, percentageScrolled / 100);

Instead of if else statement. Also as a general advice try to avoid using var, use const or let instead and if your project doesnt depend on jquery try to avoid it too.

const overlays = document.querySelectorAll(‘.colour-overlay’);
window.addEventListener('scroll', () => {

    const windowHeight = window.offsetHeight;
    const scrollTop = window.scrollTop;
    const percentageScrolled = (scrollTop * 100) / windowHeight;

    for (const overlay of overlays) {
        overlay.style.opacity = percentageScrolled / 100;
    }

});

This would be the pure js solution.

Upvotes: 1

George
George

Reputation: 6739

You can remove the if and set the opacity to the percentage divided by 100

$(window).on('scroll', function() {

  // Vars
  var windowHeight = $(window).height();
  var scrollTop = $(this).scrollTop();
  $('.colour-overlay').css('opacity', scrollTop / windowHeight);

});
.colour-overlay {
  display: block;
  width: 20px;
  height: 1200px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="colour-overlay"></div>

Upvotes: 1

Related Questions