Change CSS value according to Scroll

3

I need to, when I scroll the page, apply css to div, for example:

When the user arrives in the middle of the site, or in the desired section, apply a CSS from this point to a div , as it scrolls down the page, it changes the value of this item in CSS, the% of% of this 1px increases with each scroll, giving the impression that as the page scrolls, the item will move to the side.

Has anyone ever had to use something similar?

    
asked by anonymous 20.12.2017 / 20:26

1 answer

2

Using .scroll() of jQuery you can get the 'distance' from the top with .scrollTop() and set the properties according to that value. Ex:

$(window).scroll(function() {
    var x = $(this).scrollTop();
    $('#box').css('left', parseInt(+x) );
    if(x<100){
      $('#box').css('background', 'red' );
    }else if(x<200){
      $('#box').css('background', 'green' );
    }else{
      $('#box').css('background', 'blue' );
    }
});
#box{
    background:red;
    height:200px;
    width:200px;
    position:fixed;
    top:0px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><divstyle="height:1200px">
  <div id="box">
  </div>
</div>
    
20.12.2017 / 20:47