Introduction:
In this code tutorial, we will explore how to create a flashlight effect using mouse and touch interaction. By tracking the user’s cursor or touch position, we will dynamically update the position of a flashlight element on the screen. This effect can add an interactive and engaging element to your web projects. Join me as we delve into the steps required to implement this effect!
Quick Tip!
If you are getting started with Frontend Development here’s a book to help you master Frontend Development!
Master Frontend: Zero to Hero
Â
Things You Will Learn:
- How to detect if the user is using a touch device
- Tracking mouse and touch positions using event listeners
- Updating CSS variables dynamically to move the flashlight element
- Enhancing user experience with interactive elements
Video Tutorial:
For a more detailed visual guide, you can follow along with the video tutorial on my YouTube channel
Project Folder Structure:
To get started, let’s organize our project folder structure as follows:
- index.html: The main HTML file containing the structure of our webpage.
- style.css: The CSS file where we will define the styles for our flashlight effect.
- script.js: The JavaScript file where we will implement the functionality of the flashlight effect.
HTML:
In the index.html file, we need to create a container for our flashlight element. Add the following code snippet:
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Flash Light Effect</title> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet" /> <!-- Stylesheet --> <link rel="stylesheet" href="style.css" /> </head> <body> <div id="flashlight"></div> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusantium modi deserunt dolore iure animi aperiam, debitis optio quos quas? Sapiente corporis a illo labore assumenda est nam quisquam veniam rem voluptatum quis pariatur quae asperiores repellendus in similique, quibusdam dolorum optio incidunt laudantium! Iusto commodi odit ea sequi cupiditate alias obcaecati in qui, vero sunt sint maxime voluptatibus? Optio esse sit mollitia odit doloribus. Voluptatibus necessitatibus veritatis voluptas qui! Temporibus esse tenetur odit modi, itaque, fugiat repudiandae ex dicta ratione numquam perspiciatis! Nulla odit voluptate et in fugit recusandae accusamus aliquam vel dicta asperiores, autem quaerat doloribus, natus distinctio placeat? </p> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Magnam ducimus minus fugit, inventore amet mollitia. Illo fugiat magni pariatur maiores eum deserunt, similique amet! Dignissimos culpa fuga mollitia, maxime laborum cupiditate, nobis minus quisquam libero recusandae cum cumque consequatur vero esse quaerat odio quia eligendi porro unde! Sed veniam id odit? Pariatur cum necessitatibus corporis magnam quod dicta praesentium totam ea odio veniam dolorum doloribus delectus dolor consequatur nemo perferendis aliquam voluptatibus velit nam nostrum eveniet, dignissimos in obcaecati? Quia quidem in aliquam maxime ad. Blanditiis quis, in minima voluptates aspernatur nemo, dignissimos, possimus consequatur doloremque voluptatem recusandae perspiciatis quia. </p> <!-- Script --> <script src="script.js"></script> </body> </html>
Â
CSS:
In the style.css file, let’s define the styles for our flashlight element. Add the following CSS rules:
* { padding: 0; margin: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; cursor: none; } p { font-size: 1em; text-align: justify; line-height: 1.8em; padding: 0.2em; } #flashlight { --Xpos: 50vw; --Ypos: 50vh; } #flashlight:before { content: ""; display: block; width: 100%; height: 100%; position: absolute; pointer-events: none; background: radial-gradient( circle 9em at var(--Xpos) var(--Ypos), rgba(0, 0, 0, 0), rgba(0, 0, 0, 1) ); } @media screen and (max-width: 500px) { body { font-size: 14px; } }
Â
JS:
Now, let’s implement the functionality of the flashlight effect in the script.js file. Add the following code snippet:
let mouseX = 0; let mouseY = 0; let flashlight = document.getElementById("flashlight"); const isTouchDevice = () => { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } }; function getMousePosition(e) { mouseX = !isTouchDevice() ? e.pageX : e.touches[0].pageX; mouseY = !isTouchDevice() ? e.pageY : e.touches[0].pageY; flashlight.style.setProperty("--Xpos", mouseX + "px"); flashlight.style.setProperty("--Ypos", mouseY + "px"); } document.addEventListener("mousemove", getMousePosition); document.addEventListener("touchmove", getMousePosition);
Â
Conclusion:
Congratulations! You have successfully implemented a flashlight effect using mouse and touch interaction. Feel free to customize the styles and incorporate this effect into your web projects to add a touch of interactivity. Happy coding!
Hey, This is extremely helpful thank you. I was just wondering if is it still possible to have the flashlight cursor effect but still have elements constantly visible and not hidden by the dark black? and also still able to have the flashlight cursor be able to be in front going over the top of all elements.