E
E
Evgeny Zhurov2018-02-24 23:51:13
css
Evgeny Zhurov, 2018-02-24 23:51:13

How to make a transparency effect attached to the scroll?

Good afternoon. There is a fragment of the page, the height is always equal to the height of the browser window, regardless of the resolution. As you scroll down, this screen should gradually become transparent. When scrolling back, it's the other way around. I believe that during scrolling, the opacity value of this block should dynamically change - from 1 to 0 and vice versa. Tell me, in which direction to look, in what quantities to bind, etc., in order to realize what you are looking for? Maybe somehow convert the scroll position values ​​to parseFloat from 0 to 1? But after all, when scrolling down, the scroll position value increases, while I need the opacity value to decrease. I think this is more of a math issue than pure code, so it's important that this solution be as economical as possible in terms of performance. Think,

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
levchak0910, 2018-02-25
@Zhuroff

Take the height of this element, the "height" of the scroll, a little math and you're done.
Since the height of your element is always equal to the height of the browser window, you can usescreen.availHeight

let element = document.querySelector("Ваш элемент");
document.onscroll = () => {
    let percent = ( screen.availHeight - window.pageYOffset / 2 ) / screen.availHeight;
    if(percent <= 0) element.style.opacity = 0;
    else element.style.opacity = percent;
    console.log(percent);
};

Check out Debounce for performance.

A
Andrey Fedorov, 2018-02-24
@aliencash

If x[0..1] increases, then (1-x) decreases. There will be no brakes, it's not such a big problem.

P
Pavel Shvedov, 2018-02-25
@mmmaaak

1 - The number of scrolled pixels divided by the height of the entire document

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question