How to change a color based on the scroll position

2

Hello! I've been looking for a while and I find several things, but for what I specifically want, no. In my Tumblr blog, I want a border around the posts with approximately 5px, whose color changes based on the scroll position. I want it to be faded and so have many colors. Should I create a div for the right border? But how and what css or javascript do I use to make the "animation"? Thank you and I apologize for being so mean.

    
asked by anonymous 08.04.2016 / 23:31

2 answers

2

You can use the $ .scroll event of jQuery and the scrollTop property to know where the bar is and use that value to calculate a color of your choice. I made this example for you:

$(window).scroll(function(){
 var posicao = $(window).scrollTop();
 var cor = Math.round(posicao / 1000);
 $('#post').css('border-color', pegarCor(cor));
});
pegarCor = function(cor){
  switch(cor){
    case 1:
      return "#ff0ff0";
      break;
    case 2:
      return "#00aabc";
      break;
    case 3:
      return "#00ee54";
      break;
    case 4:
      return "#334454";
      break;
    case 5:
      return "#ff00ff";
      break;
    default:
      return "#00aa12";
      break;
  }
}
#post{
  border: 5px solid;
  border-color: #000;
  position: fixed;
  width:200px;
  height:100px
}
body{
height: 5000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="post">
Esse é o seu post
</div>
    
08.04.2016 / 23:52
0

I used the same code that LF Ziron posted and I modified so that as the page goes down using the scroll, the divs will change color

$(window).scroll(function(){
 var posicao = $(window).scrollTop();
 var cor = Math.round(posicao / 1000);
 $('.post').css('border-color', pegarCor(cor));
});
pegarCor = function(cor){
  switch(cor){
    case 1:
      return "#ff0ff0";
      break;
    case 2:
      return "#00aabc";
      break;
    case 3:
      return "#00ee54";
      break;
    case 4:
      return "#334454";
      break;
    case 5:
      return "#ff00ff";
      break;
    default:
      return "#00aa12";
      break;
  }
}
.post{
  border: 5px solid;
  border-color: #000;
  width:200px;
  height:100px;
  margin-bottom: 10px;
}
body{
height: 5000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
<div class="post">
Esse é o seu post
</div>
    
10.03.2017 / 06:37