My goal is to change the opacity of a DIV when I scroll down. It's important that the transition is smooth!
- When the
scrollTop
of the body is 400, the opacity of the Test-div should be 1. - When the
scrollTop
of the body is 800, the opacity of the Test-div should be 0.
This is what I currently have, but it doesn't work.
window.addEventListener('scroll', function() {
if (document.body.scrollTop > 400) {
var currScrollPos2 = document.body.scrollTop;
document.getElementById('test').style.opacity = -currScrollPos2 / 400 + 2;
}
}
};
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
width: 100%;
}
#test {
width: 200px;
height: 200px;
background-color: red;
position: fixed;
}
<div id="test"></div>