Change CSS value according to Scroll

Asked

Viewed 809 times

1

I need that when scrolling the page, apply css to div, example:

When the user arrives at half of the site, or at the desired Section, apply a CSS from this point to a div, as the page scrolls down, changes the value of this item in CSS, for example, increases 1px the value of left of this div with each scroll, giving the impression that as you scroll the page, the item will move to the side.

Someone has already needed to use something similar?

  • 1

    In fact what you want is a Parallax: https://plugins.jquery.com/tag/parallax/ does not only have the jQuery, has several different types of Parallax over the Internet, just know which one suits better what you need.

  • Here’s a functional example of one I found https://jsfiddle.net/byaprgu9/

1 answer

1

Using the .scroll() from jQuery you can take the 'distance' from the top with the .scrollTop() and define properties according to this 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>
<div style="height:1200px">
  <div id="box">
  </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.