Parallax Effect:
Moving Background on Mouse Position

In this tutorial, you will learn how to create a parallax effect or a moving background on mouse position using CSS and JavaScript. Watch the video below for a detailed tutorial.


HTML

<body id="container">
    <script>
        (function() {
            document.addEventListener("mousemove", parallax);
            const elem = document.querySelector("#container");
            
            function parallax(e) {
                let _w = window.innerWidth/2;
                let _h = window.innerHeight/2;
                let _mouseX = e.clientX;
                let _mouseY = e.clientY;
                let _depth1 = `${50 - (_mouseX - _w) * 0.01}% ${50 - (_mouseY - _h) * 0.01}%`;
                let _depth2 = `${50 - (_mouseX - _w) * 0.02}% ${50 - (_mouseY - _h) * 0.02}%`;
                let _depth3 = `${50 - (_mouseX - _w) * 0.06}% ${50 - (_mouseY - _h) * 0.06}%`;
                let x = `${_depth3}, ${_depth2}, ${_depth1}`;
                elem.style.backgroundPosition = x;
            }
        })();
    </script>
</body>

CSS

body {
    background-color: #99c2f8;
    background-image: url('images/airplane.png'), url('images/clouds.png'), url('images/clouds2.png');
    background-size: 50%, cover, cover;
    background-position: center, top, bottom;
    background-repeat: no-repeat;
    height: 100vh;
}

Image Source

https://lovepik.com/images/png-a-cloud.html
https://pngtree.com/so/White