How to create scroll to zoom effect?

In this tutorial, we are going to demonstrate how to create a zoom effect on mouse scroll events.

What is WheelEvent?

The WheelEvent is an event that occurs when the mouse wheel is scrolling.

What are the WheelEvent Properties and Methods?

The WheelEvent Properties and Methods and their descriptions are given below


deltaX   

            It returns the horizontal scroll amount of a mouse wheel (x-axis)

deltaY         

            It returns the vertical scroll amount of a mouse wheel (y-axis)

deltaZ

            It returns the scroll amount of a mouse wheel for the z-axis

deltaMode 

               It returns a number that represents the unit of measurements for delta values (pixels, lines, or                         pages)

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll To Zoom</title>
    <style>
        body{
            background-color: #0e273c;
        }
        .container {
            height: 100vh;
            font: 700 20px sans-serif;
            position: fixed;
            width: 100vw;
            top: 0;
            left: 0;
            box-shadow: 0 10px 20px rgb(0 0 0 / 19%), 
                        0 6px 6px rgb(0 0 0 / 23%);
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: center;
            color: #ffffff;
            background:#4a306d
        }
    </style>
</head>

<body>
    <div class="container">
        <h1> ✔ I am a heading ✌</h1>
        <div>
            <p>Hello I am zooming</p>
        </div>
    </div>

    <script>
        const container = document.querySelector(".container");
        let zoom = 1;
        const speed = 0.1;

        document.addEventListener("wheel", (event=> {
            if (event.deltaY > 0)
                container.style.transform = `scale(${(zoom += speed)})`;
            else
                container.style.transform = `scale(${(zoom -= speed)})`;
        });
    </script>
</body>

</html>

Output



Reactions

Post a Comment

0 Comments