Incorrect offsetX and offsetY values being returned on parent element's mousedown event

I'm encountering an issue with obtaining offsetX when mousedown occurs. Take a look at my code below

<!DOCTYPE html>
<html>
    <body>
        <div id="myP" onmousedown="mouseDown()">
            Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph,
            <p style="margin-left:50px">
             and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, 
            </p>
            and sets the color of the text to green.
        </div>
        <script>
            function mouseDown() {
                var left = event.offsetX;
                var top = event.offsetY;
                console.log(top+"::"+left);
            }
        </script>
    </body>
</html>

When my mousedown is over the div area, I get the correct result that I desire. However, when my mouse is over the paragraph area, I receive incorrect results. I am confused because the event should be from the parent element which is the DIV element.

Received Result Case 1: when my mouse is over DIV Element top: 17px, left: 61px

Case 2: when my mouse is over DIV Element top: 11px, left: 9px

Answer №1

Retrieve the mouse pointer coordinates using MouseEvent.offsetX or MouseEvent.offsetY, which provide the position relative to the target node's padding edge.

MouseEvent.offsetX

The read-only property, MouseEvent.offsetX, displays the X coordinate offset between the event and the padding edge of the target node.

When dealing with an element inside another element, like a <p> within #myP, expected variations in offsetX and offsetY can occur.

To consistently obtain mouse coordinates relative to #myP, deduct the values of left and top from MouseEvent.clientX and MouseEvent.clientY, respectively, retrieved by the getBoundingClientRect method.

Here is a sample code snippet for reference:

var myP = document.getElementById('myP'),
    output = document.getElementById('output');

function mouseDown(e) {
  var rect = e.currentTarget.getBoundingClientRect(),
      offsetX = e.clientX - rect.left,
      offsetY = e.clientY - rect.top;
  output.textContent = "Mouse-X: " + offsetX + ", Mouse-Y: " +  offsetY;
  console.log("Mouse-X: " + offsetX, "Mouse-Y: " + offsetY);
}

myP.addEventListener('mousedown', mouseDown, false);
body {
  margin: 0;
  font-family: sans-serif;
}

#myP {
  background: lawngreen;
  margin-left: 50px;
}

#myP > p {
  background: yellow;
  margin-left: 50px;
}

#myP > div > p {
  background: red;
  color: white;
  margin-left: 100px;
}
<div id="myP">
  Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph,
  <p>
    and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released,
  </p>
  <div>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut quaerat dolor modi et quidem repudiandae vero, recusandae laborum quae veritatis, doloribus similique accusamus quibusdam voluptate, dolore fugiat eum. Corporis, porro.
    </p>
  </div>
  and sets the color of the text to green.
</div>
<p id="output"></p>

Answer №2

To quickly address the issue, consider adding pointer-events: none; to the main children element

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

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

Problem encountered with the submission feature in Zend Framework

I am encountering an issue with the submit button icon not displaying. In my .php file, I have the following code: $submit = new Zend_Form_Element_Submit('submit'); $submit ->setLabel(Zend_Registry::get('Zend_Translate')->tra ...

What is the best way to transfer a user query to a Next.js API?

I've integrated the Listen Notes podcast-api into my Next.js api routes. My goal is for the user query entered in a form on the front-end to trigger actions in the Next.js api. For example, if a user types "history", I want the api to search for podca ...

Changing the color of options in a list when clicked: a step-by-step guide

Here is the HTML code I have: <li onclick="switchColors()"> <a class="x" href="Faculty.php">Faculty</a> </li> <li onclick="switchColors()"> <a class="x" href="Contact.php">Contact</a> </li> And here ...

My goal is to generate a collection of fullwidth ion-cards using data from an array of objects

I am attempting to iterate through an array of objects in order to generate a set of cards, either FULLWIDTH or halfwidth with the last one centered if the count is an odd number. I have created a component that contains the card layout and I am using *ng ...

What is the best method for showcasing a JSON dataset retrieved from an HTTP GET request on an empty HTML document?

I have successfully created a JavaScript file that allows me to retrieve and output data from an API. Now, I am looking for guidance on how to display this file on an HTML page. For compiling my data through the terminal, I was using Node.js. If anyone k ...

Display or conceal a button in Angular 6 based on certain conditions

In my current project, I am facing a challenge where I need to disable a button while a task is running and then activate it once the task is complete. Specifically, I want a syncing icon to spin when the task status is 'In_progress' and then hid ...

Retrieving dynamically generated form components upon submission in a React application

I am facing an issue with a modal containing a dynamically rendered form in my React component. I want to gather all the user-entered field values and send them to the backend. Below is the code for rendering the dynamic form fields: import React from &ap ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

Concentrate on utilizing the jquery tokeninput feature specifically for Chrome and Opera browsers

Encountering an issue with the tokeninput element in Chrome and Opera (Firefox is working fine). Even after selecting one or more elements, the tokeninput cannot lose focus. The cursor continues to blink even after selecting the last element, and clicking ...

What could have caused this issue to appear when I tried running ng build --prod?

Issue encountered while trying to build the ng2-pdf-viewer module: An error occurred in the webpack loader (from @angular-devkit/build-optimizer) with the message: TypeError: Cannot read property 'kind' of undefined. This error is related to A ...

Injector in Angular 6 Universal requires an additional app variable to be injected into the service

I have implemented Angular Universal and developed a PlatformService to identify the current platform I am working on. /* platform.service.js */ import { Injectable, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser, isPlat ...

Generate a JSON file using Node.js

I've been honing my skills with Node.js and express by working on a project involving a JavaScript object that generates a dropdown list. The process has been smooth so far. Recently, I integrated mongoose to create a model and saved it. Now, in my co ...

styles.css is generating an ERROR message, indicating that it is unable to read properties of null when trying to access the 'classList'

Hey there, I've been working on adding a background color change to my navbar when the scrollY exceeds 30px, and it's functioning properly. However, I'm encountering an error in the console which states that the new classList cannot be added ...

Can the color of a highchart graph be altered simply by clicking on the line?

Greetings! I am currently working on plotting a graph using highchart and I was wondering if there is a way to allow users to change the color of the plotted line by simply clicking on it and selecting a color from a color picker tool. I do not want to lim ...

Encountering the error message "React child is not valid as a Gatsby wrapRootElement" while using TypeScript with Gatsby

I've been exploring ways to implement a theme provider in Gatsby using the wrapRootElement browser API. However, I seem to have hit a roadblock as I keep encountering an error message that says "Objects are not valid as a React child (found: object wi ...

EJS is failing to render

I am currently working on a rock, paper, scissors game using Node.js on the backend with an express server, frontend.js on the client-side, and index.ejs and main.css files. My goal is to display the result of the player's decision (win, lose, or draw ...

Validating forms using Ajax in the Model-View-Controller

I am facing an issue with my Ajax form, where I need to trigger a JavaScript function on failure. The code snippet looks like this: using (Ajax.BeginForm("UpdateStages", new AjaxOptions { HttpMethod = "POST", OnSuccess = "refreshSearchResults(&apo ...

Unable to append XML nodes using jQuery's parseXML function, but able to append font

Jquery : $.get("config.xml",function(xml){ $(xml).find("config").find("images").append("<image><url>../demo/Headline/2012/12/20/0/0/A/Content/8/Web201212_P8_medium.jpg</url><name></name><redirect>none</r ...

Is it possible to dynamically register models in Vue?

When working inside a Vue-component, I encounter a scenario where I need to create a list with a variable number of entries. For example, it could look like this: <form> <input type="number" value="15" /> <input type="number" value="10" /& ...