What is parallax effect?
An image moves in a different direction at a speed when we move the cursor. It creates an illusion when the cursor moves inside a specified container.
How to create parallax effect
To create a parallax effect we can use HTML, CSS and JavaScript which is a fun easy process where can creatively show our visuals.
Structure of code
We are going to make the code into three parts below
- HTML
- CSS
- JavaScript
HTML code:
In this HTML structure we can set up the structure of our webpage including the elements you want to apply the parallax effect, Here is the code..
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mousemove parallax effect<title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="parallax" id="one"></div> <script src="script.js"></script> </body> </html>
CSS code:
CSS is used to style elements and positioning as needed.
body {
margin: 0;
padding: 0;
height: 100vh;
display: flex;
justify-content: center;
align items: center;
background-color: black;
}
.parallax {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
JavaScript:
JavaScript is used to detect the mouse movement and calculate the movement of the elements based on the mouse position. For this code script is given below..
function showTime() {
const parallax = document.getElementByID('one');
window.addEventListener('mousemove',(e) => {
let x = e.clientX / window.innerWidth * 100 - 50;
let y = e.clientY / window.innerHeight * 100 - 50;
parallax.style.transform = 'translate(${x}px, ${y}px';
});
Output:
