Tips for creating a webpage with a spotlight effect using the mouse cursor

My goal is to create a webpage that is completely dark (as in night without any light at all) and have the mouse cursor emit a light effect to illuminate the surroundings. What tools or techniques should I use to achieve this unique effect? I've searched for solutions in CSS and on the internet, but have not come across anything similar. The only option I found is this WordPress plugin, however it is fixed and does not allow for customization.

Answer №1

Although this thread is older, I found it intriguing and decided to create my own version of the effect. Check out my implementation on jsfiddle to see how I approached it.

You can view the code directly on jsfiddle, along with detailed explanations on how everything works. It's all fairly straightforward.

HTML Structure

I started by creating a div with the id light, followed by a wrapper div named content containing placeholder text (lorum ipsum).

<div id="light"></div>

<div class="content"gt;  
    <h1>Flashlight test</h1>   
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas...</p>
    <ul>
        <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
        <li>Aliquam tincidunt mauris eu risus.</li>
        <li>Vestibulum auctor dapibus neque.</li>
    </ul>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas...</p>
    
</div>

CSS Styling

In terms of styling, I first targeted the html element to set black text and background for default hiding purposes.

Then, I customized the div with the light id - making it 100px x 100px, yellow background, and circular using border-radius. The position was set as relative to allow layering over other elements. To give a default flashlight position before user interaction, I centered it on the page using top and left properties.

Lastly, I added rules to the content wrapper div, setting its position: relative and z-index: 10. This stacking order ensures the content appears above the light div due to the contrasting backgrounds.

html { 
    color: #000; 
    background-color: #000; 
}

.content {
    position: relative;
    z-index: 10;
}

#light {
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    position: absolute;
    background-color: rgb(231, 221, 122);
}

Javascript Logic

The javascript component consists of a short jQuery script spanning only 6 lines. It utilizes the mousemove() event function to update the element's offset based on mouse coordinates, effectively centering the light around the cursor and achieving the desired effect.

$(document).mousemove(function(event) {
    $('#light').offset({
        top: event.pageY - 50,
        left: event.pageX - 50
    });
});

Update with Modern Approach

Applying the same concept but leveraging newer coding practices, here's an updated version using vanilla techniques and features that were unavailable at the time of the initial response.

For a live demo, visit: https://codepen.io/bronzehedwick/pen/oNdRwYN

Modern HTML

<div id="light" style="--light-position-y: 0; --light-position-x: 0"></div>
<div class="content">
  <h1>Flashlight test</h1>
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas...</p>
  <ul>
    <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
    <li>Aliquam tincidunt mauris eu risus.</li>
    <li>Vestibulum auctor dapibus neque.</li>
  </ul>
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas...</p>
</div>

Enhanced CSS

body {
  background-color: black;
}

.content {
  position: relative;
  z-index: 10;
}

#light {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  transform: translate(var(--light-position-x, 0px), var(--light-position-y, 0px));
  background-color: rgb(231, 221, 122);
}

Revised JavaScript

var light = document.getElementById('light');

document
  .documentElement
  .addEventListener('mousemove', function handleMouseMove(event) {
    light.style.setProperty('--light-position-y', (event.clientY - 50) + 'px');
    light.style.setProperty('--light-position-x', (event.clientX - 50) + 'px');
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the text exceeds the designated block, it will be fragmented

I have always struggled with text elements not breaking when they exceed the boundaries of their parent element. I understand that setting a max-width of 100px will solve the issue, but it's not an ideal solution for me. I want the text to break only ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

What is the method for superimposing a div with a see-through input field?

I am currently designing a compact upload feature. It consists of a responsive element (actually a vue/quasar card) that adjusts in size according to the window dimensions and viewport. Within this element, there is a form containing an input field and a ...

Explore our interactive map and widget features that will seamlessly fill your browser window for a

Struggling to make a webpage with a Google Map, Chart, and Grid expand to fill the available space on the screen. Tried various CSS tricks but nothing seems to work. Check out this simplified example in JsFiddle that showcases the issue: http://jsfiddle. ...

How come only the individual top, bottom, left and right paddings function correctly while the combined padding does not respond?

Seeking to customize a button using SCSS file that is connected to HTML. This button is part of a flex layout design. The element's size is set at 83.333×16px. The box-sizing property is defined as: box-sizing: border-box; Adding padding with s ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Enhance each category changing with jQuery page transitions

Is there a way to add page transitions based on category names and quantities in PHP? For example, when clicking on the "office" category, can a popup overlay be displayed with the category name and quantity while the content loads? The focus is on creat ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

The Oracle Apex Login Interface with a Touch of Customized Styling

Currently, I'm working on creating a login page in Oracle APEX. While modifying the icon using CSS code, everything seems to be falling in place except for this one particular line: .t-Login-logo { background-image:url(#APP_FILES#LogoUpdated.jpg); bac ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

How to align buttons in the center of a Bootstrap grid column using Angular's *ngFor directive

I have been trying to center some buttons using the bootstrap 4 grid system within a column with a green border. Despite using justify-content-center, I have not been successful so far. <div class="row" style="border:1px solid red;"& ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

CSS @page does not render content within @top-center, @bottom-right, and similar positions

Currently, I am working on generating a HTML file that is print-ready and have been using CSS @page for this purpose. However, I have encountered a major issue with displaying page numbers utilizing @bottom-right and other similar solutions. Could there be ...

Creating a scrollable card layout specifically for small screens in HTML

I am looking to implement a horizontal scroll (for small screens only) within my card layout so that all cards are displayed in a single row. Here is an example: For small screens: https://i.sstatic.net/5eWyV.png So far, I have added horizontal scrolling ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

What could be causing this strange striping effect in the radial gradient?

What causes the striped effect in the radial gradient code provided on this website: click here to view body { background: rgba(216,215,221,1); background: -moz-radial-gradient(center, ellipse cover, rgba(enter code here216,215,221,1) 0%, rgba(0,9 ...