JavaScript control element using scroll

0

Hello, I was thinking of putting in a project of mine, an "effect" of controlling a certain element using the position of the scroll bar, when the user descends through the page. I tried to do some testing but ended up giving in to nothing. I think it should be easy to do and did not want to use a plugin for this.

In short: it would be a code that would calculate the percentage of the scroll position (when moved up or down) from 20 to 100 and would turn it from 0.0 to 1.0 to apply as opacity on an element or from 0 to 200 to put as "marginTop", for example. Thanks since then =)

    
asked by anonymous 10.09.2015 / 19:30

1 answer

1

I made a simple example, follow the code below.

What I did was to calculate the scroll percentage of the page I took the scroll size and divided by the amount of the page already rolled, then assign this value to opacity of div topo .

window.onload = function() {
  var tp = document.querySelector("#topo");
  var box = document.querySelector("#box");

  var tamanhoScroll = document.body.scrollHeight;

  window.addEventListener("scroll", function() {
    var scrollAtual = document.body.scrollTop;
    var porcentagemScroll = scrollAtual / tamanhoScroll;
    tp.style.opacity = porcentagemScroll;
  });
}
* {
  margin: 0;
  padding: 0;
}
body {
  background: #eee;
}
#topo {
  width: 100%;
  height: 70px;
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
  background: #fff;
  box-shadow: 3px 3px 10px #999;
}
#box {
  width: 85%;
  height: 5000px;
  background: #fff;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 30px;
  border-radius: 20px;
  box-shadow: 3px 3px 10px #999;
}
<div id="topo"></div>
<div id="box"></div>
    
10.09.2015 / 20:14