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

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

Ember JS: Master of Controlling

I am working with the following controllers: clusters_controller.js.coffee Portal.DashboardClustersController = Ember.ArrayController.extend dashboard_controller.js.coffee Portal.DashboardController = Ember.ArrayController.extend In my template, I am ...

conceal the bootstrap navigation bar while the page is being

Struggling to toggle a Bootstrap navbar on scroll? Need some guidance from the pros out there. I admit, my Bootstrap and jQuery skills are pretty basic. The browser console doesn't throw any errors, and I've experimented with fadeIn, fadeOut, add ...

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...

Partial display issue with SweetAlert popup

I am currently working on a personal project using ASP.NET MVC5 and incorporating SweetAlert for managing message alerts. However, I have encountered an issue where the alert message only appears for a brief moment when testing it on an HTML5 button with t ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

How can I create square corners within other square corners?

https://i.sstatic.net/OsDsg.png Hey there everyone, I'm curious if it's achievable to create borders like these using only CSS, without relying on a set image. If anyone has insight on how this can be accomplished, please share your knowledge. ...

"Enhance the visualization of your data with Apexcharts by accurately coloring the columns

When attempting to color the graphic using an array, only one color is applied to all three columns, despite declaring a different color for each column. options: { chart: { type: 'bar', id: 'chart', }, colors: ['#3 ...

In JavaScript, use the following code to replace "(" with "(":

Is there a way to dynamically transform the string "Test(5)" into "Test\(5\)" using JQuery or Javascript? I attempted this approach, but it did not work as expected var str = "Test(5)"; str = str.replace("(","\("); str = str.replace(")"," ...

What is the best way to show a dropdown menu on the right side of the

I developed a demo that functions properly on both desktop and mobile devices. However, I am facing an issue where the dropdown menu is not displayed when switching to the mobile version. Here is my code snippet: http://codepen.io/anon/pen/OyNLqa ...

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

Transforming an Ext.data.TreeStore data structure into a JSON format

How can I convert an Ext.data.TreeStore to a string for saving to Local Storage? I tried using Ext.encode() but it's giving me a circular structure error. Has anyone encountered this issue and found a workaround? ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Why do they call me the Commander of Errors?

Alert: PowerShell has detected that a screen reader may be in use and has disabled PSReadLine for compatibility reasons. To re-enable it, simply run 'Import-Module PSReadLine'. PS C:\Web Development> scss --style expanded "c:\W ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Trouble arises when using Wijmo's valueChanged event and data binding in Angular 2

As I was working on the following code snippet that triggers a function when the user modifies the wj-input-time value: @Component({ selector: 'my-app', template: '<wj-input-time [step]="1" (valueChanged)="test()"></wj-inpu ...

What is the best way to showcase several divs, along with their respective child elements, in an inline format?

I am struggling to get 4 div sections to display side by side by using the following CSS for the parent div: .parent { display: inline; } <div class="parent"> <div class="child"> <ul> <li>t ...

Stylist in Visual Studio Code for React applications

Whenever I try to save or format my React code using Ctrl + Shift + F, the formatting of the code below seems unusual. Is there a way to fix this issue? The original code is as follows: import logo from './logo.svg'; import './App.css&apos ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...