This code creates a captivating parallax effect on a webpage background on mouse move event. When users move their cursor, it shifts the background and content, providing a visually engaging experience. The JavaScript and CSS work together to achieve this dynamic effect, making your webpage more interactive and attractive.
You can use this code in your website’s landing page to add an eye-catching parallax effect, instantly grabbing your visitors’ attention.
How to Create Background Parallax Effect On Mouse Move
1. First, create an HTML structure with a "parallax-container"
and "parallax-content"
div elements. These will serve as the background and content for the parallax effect.
<div class="parallax-container"></div> <div class="parallax-content">2024</div>
2. In your CSS file, apply the necessary styles to create the parallax effect and style your content. You can modify the CSS rules according to your needs.
* { margin: 0; padding: 0; box-sizing: border-box; } body { position: relative; height: 100vh; overflow: hidden; } .parallax-container { width: 110%; height: 110%; background: url("https://cdn.pixabay.com/photo/2019/12/10/10/53/architecture-4685608_960_720.jpg") center center / cover no-repeat; position: absolute; left: -10%; top: -10%; } .parallax-content { color: #fff; font-family: 'Roboto', sans-serif; font-size: 5rem; font-weight: bold; text-shadow: -5px 10px 15px black; letter-spacing: 2px; position: absolute; top: calc(50% - 5rem); left: calc(50% - 5rem); cursor: pointer; }
3. Finally, use the following JavaScript code to create the parallax effect. This code responds to mouse movement, translating the "parallax-container"
and "parallax-content"
elements for a dynamic visual effect.
var getParallaxContainer = document.querySelector(".parallax-container"); var getParallaxContent = document.querySelector(".parallax-content"); getParallaxContainer.addEventListener("mousemove", function(e) { let x = e.pageX / window.innerWidth; let y = e.pageY / window.innerHeight; this.style.transform = `translate(${x * 5}%, ${y * 5}%)`; getParallaxContent.style.transform = `translate(${-x * 8}%, ${-y * 8}%)`; })
Customize the content, styles, and images to match your website’s theme.
That’s it! hopefully, you have successfully created an interactive background parallax effect. This dynamic feature will make your site more interactive and visually appealing. 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.