I'm using vanilla JS to increase a background-size value as the user scrolls down the page to create a parallax scroll effect. My function is below:
const heroBg = document.getElementById('hero');
window.addEventListener( 'scroll', function() {
while (heroBg.style.backgroundSize <= '100') {
heroBg.style.backgroundSize = 85 + window.pageYOffset/8 + '%';
console.log(heroBg.style.backgroundSize);
if (heroBg.style.backgroundSize === '100') {
console.log('too big');
break;
}
}
});
The trouble I'm having is that the while loop only appears to run once and the image stops growing well before the 'backgroundSize' hits 100.
You can't check for <=
if using strings. Also, you can't add numbers and strings; you have to use brackets.
const heroBg = document.getElementById('hero');
window.addEventListener( 'scroll', function() {
while (parseInt(heroBg.style.backgroundSize) <= 100) {
heroBg.style.backgroundSize = (85 + window.pageYOffset/8) + '%';
console.log(heroBg.style.backgroundSize);
if (parseInt(heroBg.style.backgroundSize) == 100) {
console.log('too big');
break;
}
}
});
the background size property has units of measurement, for example, px or %, but it is also a text property, and to perform a comparison operation, you need to first get rid of the units of measurement and then convert to a number. I suggest considering another option for performing the above task
const $body = document.querySelector("body");
let viewportHeight = document.documentElement.clientHeight
const bgSize = _ => $body.style.backgroundSize = `${(document.documentElement.scrollTop + viewportHeight) / document.documentElement.offsetHeight * 100 * (viewportHeight / 100)}px`
bgSize()
window.addEventListener("resize", _ => {
viewportHeight = document.documentElement.clientHeight
bgSize()
})
document.addEventListener("scroll", _ => {
bgSize()
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 300vh;
background: radial-gradient(closest-side circle, black 0% 100%, transparent 100%);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
}