BAKO Blog

JavaScript Parallax with Multiple Sections and Square Image

2022-08-05

We will show you how to implement scrolling parallax on multiple sections using JavaScript. This will be an example where background image used for parallax is square and is set to cover whole section. It is not a pure CSS parallax solution and sets background image position through JavaScript. For pure CSS solution refer to this blog post. First of all we will set background image through CSS:

section {
    background: url(parallax.png);
    background-size: cover;
    background-attachment: fixed;
}
                    

Then we select and adjust background position of elements using JavaScript. Y position is calculated by multiplying rate of scrollY versus whole path that window scrolls which in turn is calculated by substracting screen height from document height and substraction of screen height from image height. Image height in turn (since image is square and is set to fill whole screen) is either selected from screen height if screen height is larger than screen width or screen width in the opposite case:

let imageHeight
sections = document.querySelectorAll("section")

scroll = () => {
    sections.forEach(section => {
        section.style.backgroundPositionY = '-' + (scrollY/(document.documentElement.scrollHeight-innerHeight)) * (imageHeight - innerHeight) + 'px'
    })
}

;(resize = () =>{
    imageHeight = innerHeight > innerWidth ? innerHeight : innerWidth
    scroll()
})()

window.addEventListener("resize", function() {
    resize()
})

window.addEventListener("scroll", function() {
    scroll()
})
                    

Finally we add calculation of image height to resize event as well as scroll calculation which in turn is attached to scroll event. Check out parallax in action on our home page. Get in touch in case you would like this article updated or want more details through email address at the bottom of this page.

Get in touch

blog@bako.co

BAKO