Tips for creating a cursor follower that mirrors the position and size of another div when hovering over it

I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position.

The size of the cursor should match the width and height of the text being hovered over, and its position should correspond to the offset Y and X of that text while hovering.

Currently, my code is not working as expected. Any suggestions on how to improve it? Thank you for your help!

let cursor = document.querySelector('.cursorFollower');

let button = document.querySelector('.superText');
let buttonWidth = button.offsetWidth;
let buttonHeight = button.offsetHeight;
let buttonX = button.offsetLeft;
let buttonY = button.offsetTop;

document.addEventListener('mousemove',(e)=>{
  cursor.style.left = e.pageX - 10 + 'px';
  cursor.style.top = e.pageY - 10 + 'px';   
});

button.onmouseover = function(){
  button.setAttribute("style", "color: #84C4B5;");
  cursor.style.transform = 'rotate(0deg)';
  cursor.style.width = buttonWidth + 'px';
  cursor.style.height = buttonHeight + 'px';
  cursor.style.top = buttonY + 'px';
};

button.onmouseout = function(){
  button.setAttribute("style", "color: white;");
  cursor.style.transform = 'rotate(45deg)';
  cursor.style.width = '20px';
  cursor.style.height = '20px';
};
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width:100%;
  height: 100vh;
  background-color: #0A193E;
  color: white;
  font-family: sans-serif;
  font-size: 20px;
}

.superText {
  padding: 10px 20px;
  cursor: none;
  transition: all 0.2s ease;
}

.cursorFollower {
  width: 20px;
  height: 20px;
  position: absolute;
  border: 1px solid white;
  transition: all 0.2s ease-out;
  pointer-events: none;
  transform: rotate(45deg);
}
<div class="container">
  <p class="superText">Hello World!</p>
</div>

<div class="cursorFollower"></div>

Answer №1

  1. One issue that arose was the improper use of SetAttribute, which should be setAttribute. Pay attention to camel case!

  2. Another oversight is that left, top, width, and height are not element attributes; they belong in the style attribute.

Try this revised code:

button.onmouseover = function (e) {
  cursor.setAttribute("style", `left: ${buttonX}, top: ${buttonY}, width: ${buttonWidth}, height: ${buttonHeight}`);
};

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

Responsive Material-UI horizontal navigation bar

Hey there! I'm working on developing a UI using Material-UI, and I want to make it so that the menu can be collapsed into a slide-in style menu when accessed on a mobile device. Currently, I'm using tabs which allow for sliding left and right, b ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Add an ionic-slide-box to integrate Angular components

Is there a way to add a div from my controller without using a directive? var angularView = angular.element('<ion-scroll direction="y"> <ion-slide-box show-pager="false" ng-repeat="result in news.results | limitTo:1"> <ion-slide class= ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...

Space constraints within an li element

Is there a solution to resolve the unusual impact of margins/paddings? Check out this example on jsfiddle: jsfiddle. Here is the screenshot of the issue: i.imgur.com/64S8C.jpg. I want to eliminate any margins/paddings in the li element. ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

Posting Form Data with Ajax in CodeIgniter

Incorporating the CodeIgniter framework along with the jQuery Form plugin available at http://malsup.com/jquery/form/ Encountering challenges in ensuring proper functionality of a form. View <div class="row"> <div class="well c ...

The ExpressJS Req.method TypeError occurs when attempting to read the 'method' property of an undefined object

My node express server is throwing an error: Error in index.js. const bodyParser = require('body-parser'), express = require('express'), path = require('path'); const config = require('./config'); con ...

Using jQuery in CodeIgniter for form validation and AJAX form submission is an effective way to ensure

Whenever I submit the form, errors show perfectly. However, when I submit it again, the data enters the database but the else condition does not work as expected. I want to hide the form and display a success message. The first time, an error response occ ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Fetch data for Chart.js tooltips dynamically

One common way to load information for a tooltip in a chart is by using the following code snippet: window.myLine = new Chart(chart, { type: 'line', data: lineChartData, options: { tooltips: { enabled: true, mode: 'sin ...

Using scale transformations to animate SVG group elements

I am currently experimenting with an SVG example where I hover over specific elements to expand or scale them. However, I seem to have made a mistake somewhere or missed something important. Can someone offer me assistance? View the demo on JSFiddle here ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

The JSON dataset is displaying an undefined value

I am attempting to utilize the Reddit API to display data. However, when I try to show it on an alert, it returns as undefined. <!DOCTYPE html> <html> <body> <h2>Creating Object from JSON String</h2> <p id="demo">&l ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...

Resolving the Complete Cover Background Image problem

My current website has a full cover background image implemented using the following code: #back{ /* #back is a div */ position:absolute; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; backgroun ...

Submit form data asynchronously using Ajax and serialize the form data before posting

I'm currently facing an issue with posting HTML form values in my code. Everything works fine except for the fact that I can't get it to post single quotes ' . I believe this problem is caused by the usage of serialize. I've attempted c ...