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

What is it about the phone screen that makes media content so captivating?

My phone has a resolution of 2280x1080. I noticed that when using the following code, the background color changes to blue on my phone: @media (max-width: 500px) { body { background-color: blue; } } Interestingly, this feature stops working once "compute ...

Error Encountered: Anticipated 'styles' to consist of a series of string elements

I have attempted various solutions for this particular error message without any success. When launching my angular project using the angular cli via ng serve, everything runs smoothly with no errors. However, upon compiling it with webpack, I encounter th ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

toggle visibility of two div elements by clicking on them alternately

I would like to implement a flip effect similar to the one demonstrated in this example: http://jsfiddle.net/lakario/VPjX9/ The only difference I want is for the flip between the two div's (page1, page2) to occur when clicked on, rather than with a ...

Is there a way for me to determine which events are linked to an object?

I am currently utilizing jqGrid for displaying read-only data from http://www.trirand.com/blog/. However, the resizable columns are causing issues with other draggable elements on the page, as they tend to get stuck when dragged over the column resize area ...

Every time I refresh the page, my table is getting filled with blank rows

I created a simple example featuring a form and some PHP/JavaScript code. The JavaScript is used for form validation, while the PHP is utilized to update a MySQL table. function checkForm(){ var x = document.forms['form1']['first'] ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

Ways to retrieve the content and characteristics of a span element

I have this code snippet : <br> var value = $("#editor").jqxEditor('val'); value="<div><span style="font-weight:bold">Welcome</span></div>"; Now I want to extract the text inside the span tag and its font-weight a ...

Displaying a Bootstrap button and an input box next to each other

Looking for advice on aligning or arranging a button and input box side by side in Bootstrap without grouping. I've searched online for examples, but they all involve grouping of elements. jsfiddle: https://jsfiddle.net/erama035/p9dagmL3/3/ <div ...

What is the best method for storing and accessing audio files that users upload in my MERN application?

I am developing a MERN application and am looking to implement a feature that allows users to upload audio files. I have read that storing the files directly in the database or within a folder inside the app is not recommended. I need a solution that en ...

The lack of an error event being triggered by jQuery when an ajax call fails has puzzled many users

Why doesn't jQuery trigger an error event when running the following script? Even though I've set up the error event, it's not being called. In Chrome's Network tab in the Console, I see this error: GET http://www.google.com/adfdaf?c ...

Is it possible to use a PHP array as a JSON-encoded object for a select field value and interact with it using JavaScript?

I have a PHP function that retrieves database values to populate a select form field. I am attempting to fill the option elements with all relevant data from the query (id, name, min, max) without needing an AJAX request. To achieve this, I decided to json ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before. My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behav ...

Dynamic content container with customizable sidebar

I have a query that remains unanswered in my research on various CSS layout options. Hence, I decided to share it here. My ongoing project involves a fluid/fixed two-column design. The main content is placed on the left side while the sidebar resides on t ...

What are the solutions for resolving the TypeError when undefined is not an object error?

I'm currently working on a project where I need to fetch data from a JSON file using XMLHttpRequest and then store it in an array. However, I keep getting errors when attempting to do so. Take a look at this code snippet that seems to be causing the ...