Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event data.

In this hypothetical situation, let's assume that the div has a width and height of 10 units.

The goal is for the div to consistently remain centered on the cursor. To achieve this, the `left` and `top` values must be horizontally offset by half of the div's width and vertically offset by half of its height. By doing so, the div will be perfectly centered on the mouse cursor.

document.querySelector(".circle").style.left = e.x - (width / 2)

However, performing this adjustment multiple times throughout the application can become cumbersome. Is there a way to redefine the origin so that setting the `left` and `top` properties does not require offsetting by half the dimensions, as the origin would be at the center of the div itself?

I attempted to use the `transform-origin` property, but it seems to only affect CSS properties related to `transform`, rather than properties like `left`, `margin-left`, etc.

Is there a solution to eliminate the need for these offsets when positioning the div relative to the cursor?

Answer №1

One way to achieve this effect is by using the following CSS:

transform: translate(-50%, -50%);

This code calculates the percentage based on the width and height of the element itself.

Here is an example snippet demonstrating how this can be implemented:

const move = document.getElementById("move")
const mouseMoveHandler = e => {
  move.style.left = e.pageX + 'px';
  move.style.top = e.pageY + 'px';
}

window.addEventListener('mousemove', mouseMoveHandler)
#move {
  position: absolute;
  transform: translate(-50%, -50%);
}
<div id="move">I follow the cursor</div>

Answer №2

If you want to position an element absolutely in relation to a parent that is sized 0x0 and positioned relatively, you can achieve this effect by moving the parent element with your mouse cursor.

<!DOCTYPE html>
<html>
   <head>
      <style>
         .container {
            position: relative;
            width: 0px;
            height: 0px;
         } 

         .square {
            position: absolute;
            top: -10px;
            right: -10px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 3px solid blue;
         }
      </style>
   </head>
   <body>

      <div class="container">
         <div class="square"/>
      </div>

   </body>
</html>

To learn more about CSS positioning, you can visit: https://www.w3schools.com/css/css_positioning.asp

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

How to Conceal the <th> Tag with JavaScript

I attempted to conceal certain table elements using JavaScript. For <td> elements, it works fine: function hide(){ var x=document.getElementsByTagName('td'); for(var i in x){ x[i].style.visibility='hidden'; ...

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...

Maximizing page space with ReactJS and advanced CSS techniques

I'm currently in the process of learning CSS and struggling a bit with it. My main issue right now is trying to make my react components fill the entire height of the browser window. I've been using Display: 'grid' and gridTemplateRows: ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...

When an image is clicked, I would like it to redirect to a different page

In my slider image list, each image has an ID. If the ID becomes equal to a specific number, such as 24, I want that particular image to move to another page when clicked. Here is the code snippet: <?php $sql = "select * from ".$tblImages." Where cid= ...

Get the values of var1 and var2 from the URL in PHP, for example: `example.php?var1

Currently, a portion of my website operates by using GET requests to navigate to profiles or pages. However, I am concerned about the scenario where a user visits someone's profile page (requiring one GET) and then clicks on a sub-tab within that prof ...

Issue with JS jQuery: The click event on an li element within an expanded ul does not function properly

I have built a basic webpage to explore jQuery. However, there is an issue that arises when I click on the "Button: another one." It seems to interfere with the event of clicking on the li element, causing it to glitch and not respond. Here is the code: JS ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

The mat-table fails to populate with data retrieved from the rest service

I have successfully fetched an array from my REST service and displayed some information from the response on the page. However, I am facing issues populating my mat-table and I'm unsure of the cause. The mat-table was functioning properly in the past ...

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

Display Nvd3 Pie Chart percentages in decimal format

I have integrated Nvd3 into my Angular project to create various types of charts. Utilizing the angular directive from Krispo's website, I am currently working on a pie chart that displays values in percentages. However, the displayed values are round ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...

What methods can I use to prevent a JavaScript array from getting filled during page loading?

Looking for assistance to populate an array using JQuery with option values from multiple select elements. I need the array to reset and fill with new options each time a select element is used. Strangely, despite my efforts, the array appears pre-filled w ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

Socket.io is most effective when reconnecting

I am currently in the process of developing a React application that connects to a Node.js API and I am trying to integrate the Socket.io library. Following various online tutorials, my code now looks like this: API: import express from 'express&apo ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...