Javascript control element using scroll

Asked

Viewed 2,032 times

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 run some tests, but it turned out to be 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 computes the percentage of scroll position (when moved up or down) from 20 to 100 and transforms it into a value 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 =)

  • What did you try to do? There’s some code ? You’re using jQuery or neither ?

  • See if this example helps you http://jsfiddle.net/tcloninger/e5qad/

  • Emir, in his example, he gives the beginning of the animation in a certain position, but does not control it if I fool up or down in scroll =p

  • Right, the more you’ll need to adjust the logic. scrollTop will give you the scroll position with respect to the screen size. From there you only need to get the screen size with window.height. Make a rule of three and discover the %. Remembering that every time the guy rolls the bar the event will be triggered

  • Jquery all right, is the basis of all =D but did not want to use gigantic plugins to make a certain function that I’m sure can do with few lines of code

  • I asked if you are using jQuery. jQuery is not plugin, it is a library made in Javascript.

Show 1 more comment

1 answer

1


I made a simple example, follow the code below.

What I did was the following, to calculate the percentage of page scrolling I took the scroll size and divided by the amount of the page already rolled, then assign this value to the 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>

  • It was in the style I wanted! = D Your answer has already helped a lot but what if I want to limit this animation to only work between two numbers and not the whole scroll, like when the value of scrollTop is between 100 and 300.

Browser other questions tagged

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