I am trying to set the maximum scroll of an element, in this case .contain
, to match the height needed for .square
to fill the entire viewport (both width and height) on scroll. I need to figure out how I can retrieve the remaining height needed to cover the offset value of the scroll.
Here is a codepen showing what currently happens. The scroll reaches the bottom and the square fails to fill the screen. Without the offset I can get this to work perfectly (see line 17), but I'd really like to learn how I can incorporate the parallax offset/speed effect.
https://codepen.io/anon/pen/zbeyQd
The non-offset version to show how the above pen should work. Square fills the screen as the scrollbar hits the bottom: https://codepen.io/anon/pen/Rdvvom
This should do the trick
const sq = document.querySelector('.square')
const contain = document.querySelector('.contain')
//set desired scroll boundaries. can be any size
//the higher the value the longer you'll have to scroll
const scrollOffset = 250
const sqW = sq.offsetWidth
const sqH = sq.offsetHeight
const wHeight = window.innerHeight
const wWidth = window.innerWidth
contain.style.height = `${wHeight + scrollOffset}px`
window.addEventListener('scroll', (e) => {
const percentScroll = window.scrollY * 100 / scrollOffset
const width = (wWidth - sqW) * percentScroll / 100
const height = (wHeight - sqH) * percentScroll / 100
sq.style.width = `${sqW + width}px`
sq.style.height = `${sqH + height}px`
})
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.contain {
height: 100%;
width: 100%;
background-color: papayawhip;
}
.square {
width: 100px;
height: 100px;
background-color: tomato;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 0.25;
}
<div class="contain">
<div class="square"></div>
</div>