How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values.

Here is a demo showcasing my problem. Here is a snippet:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<div (mousemove)="showXY($event)"></div>`,
  styles: [`div { border: 1px solid black; height: 500px; width: 500px }`]
})
export class HelloComponent {
  @Input() name: string;

  x: number;
  y: number;
  showXY(e: MouseEvent) {
    this.x = e.offsetX;
    this.y = e.offsetY;
    console.log('x: ', this.x, 'y: ', this.y);
  }
}

How can I display the decimal precision of the x and y values when moving the mouse over the div?

Answer №1

It came as a surprise to me that MouseEvent.offset{X,Y} are said to be represented by double-precision floating-point numbers, even though I have not encountered them in practical use:

Return Value

A double floating point value. Previous versions of the specification labeled this as an integer. Refer to the Browser compatibility section for more information.

The compatibility table states that Chrome versions 56 and above have updated their internal representation to a double.

According to observations made on this inquiry, it's possible to obtain sub-pixel precision, but this seems to rely on hardware capabilities. For instance, my current setup (a basic 1080p Benq LCD monitor on Windows 10) does not provide subpixel resolution, resulting in integer values being returned.

Therefore, when transferring your application, you must consider this factor and acknowledge that subpixel resolution might only be available through progressive enhancement - potentially in limited scenarios – and round your values using Math.floor() or .ceil() otherwise.

To determine if sub-pixel capability is present, you could simply check for a decimal in the return value (e.g.,

Number.isInteger(MouseEvent.offsetX)
).

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

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

Retrieving data from notifications without having to interact with them (using Firebase Cloud Messaging and React Native)

Currently, I am able to handle messages whether the app is open, minimized, or closed. However, how can I process a message if a user logs into the application without receiving a notification? useEffect(() => { messaging().setBackgroundMessageHa ...

Strange rendering in CSS JQuery Datatable

I am encountering an issue with a DataTable from datatables.net. Each row can be selected by clicking on a checkbox, which triggers a click event. In response to the event, I add or remove a CSS class to change the appearance of the selected rows. $(".cbD ...

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

Tips for testing the website's color modifications?

I recently had the task of replacing 10 specific colors with new ones in my CSS files. I used the find and replace method to make the changes in over 300 places throughout all the files. Now, I need a way to test if all the color replacements were done c ...

I would like to create a map showing the selected locations by checking them off using checkboxes

How can I draw a road map by selecting locations with checkboxes in form.php? After posting the selected locations to map.php file and assigning them to a $location array, how do I then assign these values to the waypoints array in the javascript calcRoute ...

What is the best way to manage errors and responses before passing them on to the subscriber when using rxjs lastValueFrom with the pipe operator and take(1

I'm seeking advice on the following code snippet: async getItemById(idParam: string): Promise<any> { return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1))) } What is the ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

Display fixed information in a separate tab using express and ejs

I have an Express app that is running smoothly with a MongoDB backend, and it's able to render tables with data flawlessly. However, I've encountered an issue when trying to export a table from my database. The exported table looks something like ...

Retrieving checkbox data and transmitting it without using a form submission

I've been attempting to extract values from a checkbox group, but for some reason, it's not working as expected. Here is the approach I'm taking: Using a loop to generate checkboxes <input class="group1" type="checkbox" name="catCheck" ...

Discrepancy in div height between Chrome/Edge and Firefox browsers

I am currently in the process of designing a straightforward website layout that includes a navigation bar at the top. The main focus is on an image that needs to stretch from the bottom of the navbar to the bottom of the window, filling up the entire scre ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

What could be causing the data toggle feature in my navbar to not work on Bootstrap?

Here is a code snippet to create a simple collapsible navbar with Bootstrap 5 that includes a logout button. However, the data toggle feature for the logout button doesn't seem to work when clicked. Any suggestions on how to fix this? <!DOCTYPE ...