Set div width based on scroll position

Code: http://codepen.io/anon/pen/EjrpMM

So I am working on an interesting problem. I am working with a 2000px HTML document that has modal placement on it.

The lightbox div's width is 80% and it sits motionless.

The goal is to scroll the page in order to control the width of the div based on the scroll position. It only ranks third at the bottom of the page.

I found it difficult to figure out the correct equation or formula for this and was looking for help.

I'm currently trying to look at window.pageYOffset to add 2.5% to the div when zoomed in, and minus 2.5% when scrolling back to get it back to 80% width.

However, something is not working correctly. I saw if the community has any ideas to help solve the problem.

I don't use any framework for this.

Here is my javascript:

var lightBox = document.getElementById('lightBox'),
count = 80,
num = window.pageYOffset;

document.addEventListener('scroll', function(e) {
  var offset = window.pageYOffset;

  num >= offset ? count += 2.5 : count -= 2.5;
  num = offset;

  lightBox.style.width = count + '%';
});

      

Look at the code here in this codep

http://codepen.io/anon/pen/EjrpMM

Thank!

+3


source to share


3 answers


You just need to change

+= 2.5 and -=2.5 to += 0.7 and -= 0.7

      



When I checked your code I did it and it worked.

0


source


Scroll event that fires once, independent of the scroll scroll. For example. if you scroll the scrollbar 1px or scroll 100px using the mouse scroll event will be fired once.

So, if you want stable results, you will need to calculate your div width based on the scroll position ( window.pageYOffset

).

Check out the codepen fork . I assumed the div

width should be at the end of the page 50%

.



Main part:

var lightBox = document.getElementById('lightBox');
var upperBound = 80;
var lowerBound = 50;

var tickValue = (upperBound - lowerBound) / window.innerHeight;

document.addEventListener('scroll', function(e) {
  var offset = window.pageYOffset;
  var count = upperBound - offset * tickValue;

  lightBox.style.width = count + '%';
});

      

Important note: for the crossbrowser method to get innerHeight

you can check this answer

0


source


It's a simple equation. Let f : scroll |-> f(scroll)

is a function that gives you the width of your div. You want f(0) = 0.8, f(2000)= 1/3

.

Let's say you want the progression to be linear, so f(scroll) = a*scroll + b

you can easily infer that b = 0.8

and a = (1/3 - 0.8)/2000 = -0.000233

. Now for any scroll value you can find the width of your div.

Now you can change the values ​​if you like f(scroll) = (minWidth-maxWidth)/pageLength * scroll + maxWidth

.

0


source







All Articles