Unable to get pseudo elements to track mouse movements

I'm trying to create a button with an interesting hover effect that moves along with the mouse cursor.

However, I'm facing difficulties in making the button move according to the mouse movements.

<div class="main">
  <div class="button">
    Explore the entire collection
  </div>
</div>

.main {
  width:100vw; height:100vh;
  display:flex;
  align-items:center;
  justify-content:center;
}

.button {
  padding:32px;
  background-color:green;
  color:white;
  position:relative;
  &:after {
    content:'';
    display: block;
    height:100%;
    width:100%;
    position:absolute;
    left:10px;
    top:10px;
    background-color:yellow;
  }
}
const btn = document.querySelector('.button');

const btnAfterStyle = (window.getComputedStyle(btn, ':after'));
console.log(btnAfterStyle.getPropertyValue('top'))

btn.addEventListener("mousemove", function( e ) { 
  console.log(e.clientX);
  btnAfterStyle.getPropertyValue('top') == `${e.clientY-20}px`;
  
  btnAfterStyle.getPropertyValue('left') == `${e.clientX-75}px`;
 
});

There are no errors in my code, but the properties are not updating as expected.

Any suggestions or solutions? Thank you!

Answer №1

To update the properties, you can utilize the .style attribute

const btn = document.querySelector('.button');

const btnAfterStyle = (window.getComputedStyle(btn, ':after'));

btn.addEventListener("mousemove", function( e ) { 
 // btnAfterStyle.getPropertyValue('top') = `${e.clientY-20}px`;
    btn.style['top'] = `${e.clientY-0.5}px`;
    btn.style['left'] = `${e.clientY-0.5}px`;
 // btnAfterStyle.getPropertyValue('left') = `${e.clientX-75}px`;
 
});
.button {
  padding:32px;
  width : 200px;
  background-color:green;
  color:white;
  position:relative;
}
<div class="main">
  <div class="button">
    See the entire collection
  </div>
</div>

Answer №2

If you're looking to adjust the positioning of a pseudo element, using CSS variables can help achieve the desired effect.

This code snippet demonstrates setting custom variables (--x and --y) to control the position of the pseudo element by referencing them with top: var(--y) and left: var(--x).

It takes into account that the pseudo element is positioned relative to the button itself, requiring adjustments based on the button's coordinates.

const btn = document.querySelector('.button');
const rect = btn.getBoundingClientRect();
const btnY = rect.top;
const btnX = rect.left;

btn.addEventListener("mousemove", function(e) {
  btn.style.setProperty('--y', `${e.clientY - btnY-20}px`);

  btn.style.setProperty('--x', `${e.clientX - btnX -75}px`);

});
.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button {
  padding: 32px;
  background-color: green;
  color: white;
  position: relative;
}

.button::after {
  content: '';
  display: block;
  height: 100%;
  width: 100%;
  position: absolute;
  left: var(--x);
  top: var(--y);
  background-color: yellow;
}


}
<div class="main">
  <div class="button">
    Explore the collection
  </div>
</div>

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

Embed the image within the form input

I am trying to incorporate an SVG image into a bootstrap form input, similar to this example: https://i.sstatic.net/7ZSRH.png This is the HTML code: <div class="col-md-6"> <div class="subscribe-wrapper subscribe2-wrapper mb-15&q ...

How can the useEffect Hook be utilized to perform a specific operation just one time?

My goal was to have a modal popup appear if the user moves their cursor outside of the window. I experimented with the following code: React.useEffect(() => { const popupWhenLeave = (event) => { if ( event.clientY <= 0 || ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Customize MUI Tabs to resemble the design of Bootstrap Nav Tabs

Looking to customize Material UI Tabs to resemble Bootstrap Tabs. Made significant changes, but struggling with removing the border-bottom on the activeTab. In Bootstrap, they use marginBottom: -1px on the active tab, but it doesn't work for me. Any s ...

Create an ordered series based on a JSON data

There is a specific requirement from the client that each separate content text should start with a new sequence number. In order to achieve this, I have a sample JSON response from the backend that needs to be iterated over recursively. How can I generate ...

Ensuring that the initial column of a table remains in place while scrolling horizontally

Thank you for taking the time to read this. I am currently working on a table within a div container (div0) where the data is dynamically generated, resulting in a table with unpredictable height and width. The outer div allows for both vertical and horizo ...

In Javascript, objects within local scope cannot be accessed from nested functions

I'm currently working on a function that is meant to retrieve an object from a PHP file located on a different page. I've implemented the jQuery ajax function to handle the JSON retrieval, and it seems to be functioning as intended. However, I&ap ...

Angular 2.0 in conjunction with D3.js does not style SVG elements using CSS

Currently, I am utilizing Angular 2.0 TypeScript along with the d3.js library to create graphics. My main focus is on applying CSS to the axis (especially shape-rendering: crispEdges;). Do you have any suggestions? Check out the code below: var vis = d3 ...

Deploy a Next JS website within a subdirectory using traefik

I'm having trouble publishing a website in a subfolder (example.com/sitename) using Traefik. The website is built with Next JS. When I deploy, all script links in the built site ignore the folder (sitename). For example, a js script named generatedf ...

Implementing object rotation towards a target using three.js

Even though I have been working with vector graphics for over 13 years now, I still find it challenging to grasp how three.js handles things. One thing I am trying to achieve is having an object that always faces the camera and rotates accordingly. In ano ...

Implement intro.js on a bootstrap dropdown component

I'm having difficulty using intro.js with dropdown elements. I came across a similar question on this topic with no answer: IntroJS Bootstrap Menu doesnt work If you want to see the error in action, follow these steps: Click on "Aide" (The green bu ...

Instructions on implementing linear gradient color borders on buttons using Tailwind CSS

Currently experimenting with Nextjs and tailwind css. I managed to create a basic web page using these technologies, but now I'm stuck on attempting to add a linear gradient color border to a button in tailwind css. Any ideas on how I can achieve this ...

CSS to resolve HTML alignment problems

I am new to HTML and CSS, trying to practice formulating a few things but my efforts are proving futile. Below is the code and images for your reference. I would appreciate your opinion. .container { display: block; width: 200px; height: 120px; } ...

Displaying the information fetched using axios on the screen using node.js

Is there a way to display the information from the input boxes in the image on the screen using node js? ...

Unable to choose an item from a table using the "editable-checkbox" option

Seeking assistance with the following situation: I am trying to access a table, locate the row where the status is 'GOO', and then activate the editing of this row by clicking on a button. After that, I need to click on a checkbox in the last co ...

Changing the background-color with CSS class toggling

I'm having an issue with an element that is supposed to change its background color from "lightGreen" to "red" upon hovering. However, even though the class is being added properly, the color remains lightGreen. It's worth noting that the elemen ...

What is the method to invoke a function within a factory in angularjs by using a string parameter?

I have a complex logic that I want to encapsulate in an AngularJS factory for easy use with dependency injection. The challenge is that the logic is dynamic, so I don't know in advance what functions will be available. What I have is a string represen ...

When using a jQuery function, remember to always return false

I'm currently developing a forum and looking to implement client-side form validation. However, I'm unsure about how to validate the form before submission. I've tried using an 'on' function, but I need a way to notify the user if ...

The hyperlink function is malfunctioning when used with the embed tag in both Internet Explorer and Chrome browsers

<param id="movie" name="movie" value='<%= Me.ResolveUrl(Me.BannerPath)%>'> <a href='http://<%= BannerTargetUrl%>' target="_blank"> <embed wmode="transparent" src='<%= Me.ResolveUrl( ...

What specific features does CSS3 offer in terms of background-size properties?

Let's delve into my knowledge: $, like in font-size: 14$; em, as in margin: 2em; What other units are out there? ...