How to Create a Parallax Effect using HTML, CSS, and JavaScript?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to learn about parallax effects and how to create them using HTML, CSS, and JavaScript. We will be using the mouse-move event to show the parallax effect. During the parallax effect, two different images move in parallel to each other. Both the images will be working parallel and making the same transitions. The only difference will be they move in the opposite directions.

Parallax effects are used for making the websites better in terms of User Experience and enhancing the interactivity level of the website. We can move the foreground and the background images at different speeds in different directions. There can be multiple combinations of the parallax effect like moving a text with an image or an image with an image.

Example

In the below example, we have a Parallax Effect using two images. Both the images move in opposite directions with the same speed.

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <style>
   * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: sans-serif;
   }
   body {
      background-color: lightgrey;
   }
   .mouse_move {
      position: relative;
      width: 100%;
      height: 100vh;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
   }
   .mouse_move h2 {
      position: relative;
      font-size: 40px;
      color: black;
   }
   .mouse_move img {
      position: absolute;
   }
   #img1 {
      top: 80px;
      left: 80px;
      height: 250px;
      width: 250px;
   }
   #img2 {
      bottom: 80px;
      right: 80px;
      height: 250px;
      width: 250px;
   }
   </style>
   <title>Parallax Effect</title>
</head>
<body>
   <div class="mouse_move">
   <img
      id="img1"
   src="https://www.tutorialspoint.com/assets/questions/media/64678/5.png"
   class="mouse"
   value="7"/>
   <h2>Welcome To Tutorials Point</h2>
   <img
      id="img2" src="https://www.tutorialspoint.com/images/logo.png" class="mouse" value="-7"/>
   </div>
   <script type="text/javascript">
   document.addEventListener("mousemove", parallax);
   function parallax(event) {
      this.querySelectorAll(".mouse").forEach((shift) => {
         const position = shift.getAttribute("value");
         const x = (window.innerWidth - event.pageX * position) / 90;
         const y = (window.innerHeight - event.pageY * position) / 90;
         shift.style.transform = `translateX(${x}px) translateY(${y}px)`;
      });
   }
   </script>
</body>
</html>

Output

raja
Updated on 26-Apr-2022 06:45:17

Advertisements