0

I need a jquery code snippet that alters a css value (from min value to max value - both can be declared) when user scrolls a page. According to the scroll position, the CSS value (for example height) of a div should be changed "in realtime".

Let's say the scolling becomes a range between 0 and max. 200px. (When scrolled more then 200px it shouldn't affect the CSS value anymore.)

And the CSS value besomes a range between 300px and 600px.

This is what the jquery routine should do:

Scroll=0px: CSS value=300px
Scroll=100px: CSS value=450px
Scroll=200px: CSS value=600px

It's probably a very easy snippet. Could somebody maybe help me out. That would be super. Thank you very much! Best regards, Pierre

3
  • Are your scroll values supposed to be distance from the top of the viewport? Commented Nov 27, 2018 at 15:05
  • Welcome! Please see How to Ask, including how to include an minimal reproducible example. As it stands, this question is too broad and requires someone to do a lot of work before they can offer an answer. Commented Nov 27, 2018 at 16:30
  • "Are your scroll values supposed to be distance from the top of the viewport?" Yes! Commented Nov 27, 2018 at 19:03

1 Answer 1

1

You can use the $(window).scroll(function() to trigger on scroll event and then get the scroll amount for desired div or whatever needed, in this example i used window. Then check the scroll amount if(scroll >= minScroll && scroll < MaxScroll) and perform desired action

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  console.log(scroll);
  
  if(scroll >= 200 && scroll < 700){
    $(".box").css("background-color", "blue");
  }
  
   else if(scroll >= 700 && scroll < 1300){
    $(".box").css("background-color", "green");
  }
  
   else if(scroll >= 1300 && scroll < 2000){
    $(".box").css("background-color", "purple");
  }
  
   else if(scroll >= 2000 && scroll < 3000){
    $(".box").css("background-color", "orange");
  }
});
.box{
  background-color: orange;
  height: 3000px;
  width 100%;
  overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! In my case it is crucial that the css value is being changed continuously / linear without fix steps.
@PierreHansen - case in point to my comment above: if your comment is accurate, then the question as asked is unclear, and needs to be sharpened so folks who are trying to help don't waste their time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.