Update Mouse Pointer Location

Is there a way to create a function that updates the cursor position to the center of a background circle when hovering over the navbar? I need some assistance with this, please.

const cursor = document.querySelector('#cursor');

        document.addEventListener("mousemove", function(e) {
        cursor.setAttribute("style", "top: " + (e.clientY - 10) + "px; left: " + (e.clientX - 10) + "px;")
        })
        document.getElementById("navbarimg").addEventListener("mouseover",function(e) {
        cursor.classList.toggle("hover")
        })
        document.getElementById("navbarimg").addEventListener("mouseout",function(e) {
        cursor.classList.toggle("hover")
        })
body{margin:0;height:100vh;background:rgb(27,27,27);}
            #cursor{width:30px;height:30px;border:2px solid gray;border-radius:50%;position:fixed;transition-duration: 100ms;transition-timing-function: ease-out;}
            #navbarimg{position:absolute;top:50%;left:50%;transform:tranlate(-50%,-50%);}
            #cursor.hover{width:100px;height:100px;opacity:0.1;background-color:gray;}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8>
        <meta name="viewpoint" content="width=device-width, initial-scale=1.0"&r
        <title>Cursor</title>
    </head>
    <body>
        <div id="cursor"></div>
            <div class="nav">
            <a href="../"><img id="navbarimg" src="navbar.svg" alt="navbar"></a>           </div>
      </body>

Answer №1

To easily center the cursor, just include

transform: translate(-50%, -50%);
in the styling without the need for any offset adjustments.

const cursor = document.querySelector('#cursor');

document.addEventListener("mousemove", function(e) {
  cursor.setAttribute("style", "top: " + (e.clientY) + "px; left: " + (e.clientX ) + "px;")
})
document.getElementById("navbarimg").addEventListener("mouseover", function(e) {
  cursor.classList.toggle("hover")
})
document.getElementById("navbarimg").addEventListener("mouseout", function(e) {
  cursor.classList.toggle("hover")
})
body {
  margin: 0;
  height: 100vh;
  background: rgb(27, 27, 27);
}

#cursor {
  width: 30px;
  height: 30px;
  border: 2px solid gray;
  border-radius: 50%;
  position: fixed;
  transform: translate(-50%, -50%);
  transition-duration: 100ms;
  transition-timing-function: ease-out;
}

#navbarimg {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#cursor.hover {
  width: 100px;
  height: 100px;
  opacity: 0.1;
  background-color: gray;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewpoint" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Cursor</title>
</head>

<body>
  <div id="cursor"></div>
  <div class="nav">
    <a href="../"><img id="navbarimg" src="navbar.svg" alt="navbar"></a>
  </div>
</body>

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

Using a Hook inside a React function is not possible

I encountered an error message known as the "invalid hook call error" while using the useEffect hook in my code. According to the documentation, this issue usually arises due to either a version mismatch or incorrect function calls. Could someone kindly r ...

Sending data from TextBoxFor to controller with @Ajax.ActionLink in MVC

I’ve gone through numerous questions dealing with the same issue, yet none of them seem to solve my problem (or I’m completely missing the point). As the title suggests, I am attempting to transfer the value from a TextBoxFor to my controller using an ...

I find it impossible to avoid using the withRouter and withAlert functionalities in Reactjs

When using withRouter, the alert.success property is not accessible. A TypeError is thrown with the message "Cannot read property 'success' of undefined". This issue prevents the successful display of alerts in my application. The error occurred ...

What is the process for uploading content when an image is clicked on?

Is it possible to assign a name to a variable on click of an image? Instead of using a text field and submit button, I want to achieve this functionality by simply clicking on the image itself. I tried the following code but it doesn't seem to work. A ...

Using EJS variables within script tags to assign an array to a variable results in converting the array into

When I needed to pass a variable to the script tag in the EJS file, I used the question array (which I inexplicably called object in the variable name) that I had to work with. This was achieved by using '<%-varname%>'. However, my goal was ...

Tips on assigning html actions/variables to a flask submit button

I am facing an issue with my Flask app where the form submission process takes a while for the backend to process. In order to prevent users from refreshing or resubmitting, I want to display a loading gif during this time. The current HTML code for my fl ...

Creating a new string by combining elements from an array using JavaScript

I need help creating a dot file from a string array. edges =[["Source1" ,"interfaceA" , "high" , "Sink1" , "interfaceB" , "high"], ["Source2" ,"interfaceC" , "hig ...

How can Python be used to read/modify a local file in HTML5 Local Storage?

After completing an Ubuntu Webapp project, I am interested in creating a Preferences dialog using a clever workaround. I have discovered that values can be stored/retrieved from the web app using HTML5: if (localStorage.getItem('showNotifications&ap ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

Switching <div></div> to inline-block doesn't seem to have any effect (repl.it provided)

Could someone assist me with changing the div element to an inline block? I've been having trouble with it. For reference, here is my repl.it: https://repl.it/repls/AwareContentTechnician ...

Display a div element using AngularJS

Looking for a way to display a div using AngularJS, I came across some solutions on StackOverflow. However, implementing them did not work in my case. Here is my HTML code: <div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" clas ...

Navigating with React Router DOM version 6 and organizing routes with layouts

I am currently working on a page structure that consists of the following: Login (Root page) Forget password Dashboard (Wrapper layout needed) Orders (Wrapper layout needed) Specifically, the orders page and dashboard require a wrapper layout. Below is ...

A guide on extracting individual Json fields and assigning them to separate variables

I have a JSON object that I need to break down into individual fields and then use each field separately. However, the code I wrote below is not functioning correctly and returns "undefined" in the alert message. This is my code snippet: $( document ).r ...

What are the best strategies for ensuring this website is fully optimized for all devices

Hi there, I've been struggling to make the header on my website responsive, but it doesn't appear to be functioning properly. Any assistance would be greatly appreciated. <!DOCTYPE html> <html lang="en"> <head> <meta name="v ...

Display or Hide certain Items/Elements depending on the chosen Category

I have multiple images within a div, each image belonging to a specific category. I want to display only the images from a selected category and hide all others. Initially, all images are in the category all. When selecting the category blue, for example, ...

Steps for updating the text of a dropdown button to display the name of the selected item:

I have been searching for a clear answer to this question, but I couldn't find one. So here I am seeking help: I have a button that functions as a dropdown menu: <body> <div class="dropdown"> <button onclick="changeDropdownVisibilit ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

I need to swap out a pair of images simultaneously

Is it possible to use JavaScript to change the images in imageBox1 and imageBox2 simultaneously when clicking a button? For example, if I click "hello", I want image1-1 and image2-1 to be displayed together. And if I click "world", then image1-2 and ima ...

Update the knockout values prior to submitting them to the server

Imagine having a ViewModel structured like this with prices ranging from 1 to 100... var Item = { price1: ko.observable(), price2: ko.observable(), price3: ko.observable(), ... ... price100: ko.observable(), name: ko.observable ...