When traversing across different child elements, the MouseEvent.offsetX/Y values get reset to 0

Check out this interactive example.

The demonstration includes a main div with 3 child divs. A click event is triggered on the main div, but instead of displaying alerts with the mouse position relative to the parent div as expected, it shows the position relative to the child div that was clicked.

const parent = document.getElementById('main');
parent.addEventListener('click', handleMouseClick);

function handleMouseClick(e) {
    alert(e.offsetX, e.offsetY);
}

Desired behavior: Clicking on any child div should provide the click position relative to the parent div (#main).

Current issue: The offset values always reflect the position relative to the clicked child div, not #main.

What causes this discrepancy? Is there a solution to ensure accurate tracking of the mouse position in relation to the parent div, even when scrolling occurs?

Answer №1

To achieve your desired outcome, follow these steps:

function handleMouseClick(e) {
  child = e.target.getBoundingClientRect();
    alert(e.offsetX+child.left, e.offsetY+child.top);
}

This event is triggered for the child element that is on top. By using getBoundingClientRect() on the child element, you can access its left and top properties to determine its position relative to its parent. I hope this explanation clarifies things!

Edit: If the parent of event.target is not positioned at (0,0), you will need to consider the offset of the parent (and potentially ancestors) to accurately locate the mouse click position. To navigate through a DOM object's parents, use the parentElement property (e.target.parentElement).

For instance:

function handleMouseClick(e) {
  childBounds = e.target.getBoundingClientRect();
  parentBounds = e.target.parentElement.getBoundingClientRect();
   alert((e.offsetX + childBounds.left - parentBounds.left) + ", "+ (e.offsetY + childBounds.top - parentBounds.top));
}

Answer №2

Enhance your child element by adding a CSS attribute:

.child {
  pointer-events: none;
}

Check out this CodePen example for reference.

Answer №3

CalibrationData:{  
       SensorId:    3,
       CalibrationType:    0,
       Width:    0,
       Height:    0,
       ShiftX:    0,
       ShiftY:    0,
       TableSize:    0,
       RegisterValues:    {0, 0xd048d035, 0, 0x00480041, 0},
       GainTable:    {

            0x99, 0x6d, 0x94, 0x63, 0xa1, 0x62, 0x8b, 0x5f, 0x1a, 0x5d, 0xb2, 0x54, 0xf2, 0x53, 0xba, 0x51, 
            0x0c, 0x4f, 0x59, 0x48, 0x73, 0x47, 0xba, 0x45, 0xa7, 0x45, 0xee, 0x3f, 0xec, 0x3e, 0x7a, 0x3d, 
            0xcb, 0x3e, 0x03, 0x3a, 0x04, 0x39, 0xd4, 0x37, 0x23, 0x3a, 0xf5, 0x35, 0x09, 0x35, 0x0c, 0x34, 
            0x69, 0x37, 0xac, 0x33, 0xc0, 0x32, 0xde, 0x31, 0x8d, 0x36, 0x0b, 0x33, 0x10, 0x32, 0x5a, 0x31, 
            0x85, 0x37, 0xc4, 0x33, 0xd1, 0x32, 0x24, 0x32, 0x2a, 0x3a, 0xfa, 0x35, 0x0f, 0x35, 0x30, 0x34, 
            0x02, 0x3f, 0xce, 0x39, 0xe8, 0x38, 0x93, 0x37, 0xb8, 0x45, 0xfd, 0x3f, 0x3e, 0x3f, 0x98, 0x3d, 
            0x25, 0x50, 0xd6, 0x48, 0x16, 0x48, 0x4a, 0x46, 0x17, 0x5e, 0x7f, 0x55, 0xd1, 0x54, 0x48, 0x52, 

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

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

Steps to restrict input in a text area to only backspace and cursor movements

I'm in search of a jQuery function that restricts movements to only arrow keys and backspace within a textarea. However, there seems to be an issue with the arrow key movements not functioning correctly. function moveArrow(e){ if(e.which >= 3 ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

Node.js equivalent of the `Pattern.compile` function

This Java/Android code works perfectly to extract all text between <tag> and </tag> What is the equivalent of this Java code in Node.js/Javascript? private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>"); pri ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git. Here's a snippet of my .env file: API_TOKEN=secrettokengibberish When working on my Angular controller, I need to retrieve this variable for my AJAX call. This i ...

A <div> with relative positioning is inhibiting the visibility of absolutely positioned elements without any visible overlap

Recently, I encountered a strange issue on my webpage: Image of page The lines on the left side are supposed to be displayed behind or on top of the text box. However, when I increase their z-index, the lines extend all the way to the top of the page and g ...

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

Enhance your mouse movement for optimal efficiency

I am looking to implement a feature on a webpage where a menu is displayed whenever the cursor is near the edge of a <div>. One way to achieve this is by using the .mousemove function to track the cursor position and show/hide the menu based on proxi ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...

Retrieve the store location value when clicked (Javascript)

I'm currently struggling to capture the value of a click in my Javascript code and I could use some help understanding how to achieve this. <span class="s-link"> <a class="s-link-pim-data" href="javascript:void(0);" target="_blank" title="O ...

Accessing JSON data from a URL in AngularJS

Just dove into the world of fetching and displaying JSON data in my AngularJS app for the first time, but unfortunately, no data is showing up. Here's the code I have implemented: HTML <div ng-app="myApp" ng-controller="custom ...

Display an input field in VueJS with a default value set

Dealing with a form containing various editable fields, I devised a solution. By incorporating a button, clicking it would conceal the label and button itself, while revealing a text box alongside a save button. The challenge lays in pre-filling the textbo ...

using angularjs to dynamically apply css styles

Below is the input I have: The HTML code is shown below: <input type="number" ng-class="{negative: amount < 0}" ng-model="amount"/> This is the corresponding CSS code: .negative { color: red; } If the amount is positive, no specif ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Appending a forward slash at the end of a URL seamlessly directs the user to a serendipitous webpage experience, while

I'm currently developing a project on this website: Interestingly, when you append a forward slash to the end of the URL, all the images mysteriously disappear. Consequently, I am unable to include Google AdWords tracking code at the end of any URLs: ...

Implementing the rotation of an element using 'Transform: rotate' upon loading a webpage with the help of Jquery, Javascript, and

A div element designed to showcase a speedometer; <div class="outer"> <div class="needle" ></div> </div> The speedometer animates smoothly on hover; .outer:hover .needle { transform: rotate(313deg); transform-origin: ce ...

Module cannot be resolved within react-viro

Having some issues running this application and receiving an error message. View the app code on GitHub here: https://github.com/vnovick/pile-blocks-ar I have followed the asset import instructions outlined here: . Despite following the steps correctly, I ...