This Vanilla JavaScript code snippet helps you to create a simple parallax scrolling effect. It parallax the header image on scroll event with CSS transformation property.
How to Create Simple Parallax Effect in Vanilla JavaScript
1. First of all, create header element with a class name “parallax-wrapper” and place a div element with a class name “parallax” inside it. The parallax element is the header element of your hero section. Create the main element just after the header and place your content inside it.
<header class="parallax-wrapper"> <div class="parallax"> <h1>This header has parallax effect</h1> </div> </header> <main> <p>Because vanilla JS is awesome and nobody should have to import a whole library when you only need to write 6 lines of code. Voilà.</p> </main>
3. Style the parallax header using the following CSS. Set the background image for the parallax class as define below. You need to set the minimum height of the parallax container in order to display your background image.
.cd__main { flex-direction: column !important; } .parallax-wrapper { overflow-y: hidden !important; } .parallax { background-image: url('https://placeimg.com/1000/400/tech'); background-size: cover; background-position: center; height: 250px; } /* Only for the pen */ html, body { margin: 0; min-height: 100%; font-family: sans-serif; } main { min-height: 500px; background-color: #2b2d42; } .parallax { display: flex; flex-direction: column; justify-content: center; text-align: center; } .parallax h1, .parallax p { margin: 0; color: #fff; } p { font-weight: 500; font-size: 1.2em; max-width: 600px; margin: 0 auto; text-align: center; line-height: 1.6; padding-top: 80px; }
3. In last, add the following JavaScript function between the <script> and </script> tag before closing the body tag and done.
// Parallax effect // Adapted from @ilonacodes article -> https://link.medium.com/7fFiON6Q1X // Update : added throttle to increase performance window.addEventListener('scroll', throttle(parallax, 14)); function throttle(fn, wait) { var time = Date.now(); return function() { if ((time + wait - Date.now()) < 0) { fn(); time = Date.now(); } } }; function parallax() { var scrolled = window.pageYOffset; var parallax = document.querySelector(".parallax"); // You can adjust the 0.4 to change the speed var coords = (scrolled * .4) + 'px' parallax.style.transform = 'translateY(' + coords + ')'; };
That’s all! hopefully, you have successfully created simple parallax scrolling effect. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.