How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor:

function displayCursorCoordinates(e) {
  var x = event.clientX;
  var y = event.clientY;
  var coordinates = "(" + x + ", " + y + ")";
  document.getElementById("box").innerHTML = coordinates;
  var bx = document.getElementById("box");
  bx.style.left = e.pageX - 50;
  bx.style.top = e.pageY + 20;
}

function hideCoordinates() {
  document.getElementById("box").innerHTML = "";
}
div.relative {
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
}

div.abs {
  position: absolute;
  top: 100px;
  right: 50px;
  width: 200px;
  height: 100px;
  background-color: yellow;
}
<body onmousemove="displayCursorCoordinates(event)">
  <div class="relative">
    <div class="abs" onmousemove="displayCursorCoordinates(event)" onmouseout="hideCoordinates()"></div>
  </div>
  <div id="box" style="width:100px; height:30px; position:absolute"></div>
</body>

I want the coordinates to only show when the cursor is positioned over the yellow rectangle. If I modify

<body onmousemove="displayCursorCoordinates(event)">
to <body>, the coordinates are hidden. How can I ensure that the coordinates are only visible when hovering over the yellow rectangle?

Answer №1

To enhance performance, consider transferring the onmousemove event listener from the body element to the specific element you wish to monitor - for example, div.abs.

It is advisable to avoid using the onmousemove attribute and instead opt for a pure JavaScript solution to maintain a cohesive structure. You could try something like the following code snippet (not tested)

var elementToMonitor = document.querySelector(".abs");
elementToMonitor.addEventListener("mousemove", ShowCoordinates);

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

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

What could be causing the header's height to remain unchanged when using a percentage for its size?

I'm having trouble creating a header that takes up 20% to 40% of the body. When I try using percentages, it doesn't work but it works fine with pixels. Can someone explain why percentages aren't working for this? *{ margin:0; padding: ...

Is there a way for me to retrieve the value nested within an object within another object from this Api response?

Hey there, I'm currently struggling to retrieve the value of faceit_elo from within the csgo object. I attempted using data.games.csgo.faceit_elo but unfortunately it didn't yield any results. Any suggestions on how to access this value would be ...

What is the best way to retrieve data from an Express endpoint within a React component?

I am working on integrating a React component with an Express endpoint that returns the string "sample data". The goal is to call this endpoint from my React app, store the text in state, and then display it on the screen. Here is my component: class App ...

issues with updating a MongoDB collection

One challenge I'm facing with my social media app is that I have two separate collections - one for users and the other for user posts. When I update information in a user's collection, it should also reflect in the corresponding posts (as the po ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

Twitter-Bootstrap: implementing text underlines for thumbnail captions

While experimenting with Bootstrap, I aimed to create a layout similar to ; a grid featuring bordered panels containing text and images. After some research, I concluded that Bootstrap's Thumbnail component would be the most suitable choice for my pro ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Creating a dropdown menu and adjusting the content below

Feeling stuck in one place with my code here: link The side navbar animation is almost what I want, but clicking one option opens all of them. Hoping for a similar effect like this page: link $(document).ready(function() { $('.interfejs, .proces ...

Struggling to use the innerHTML method to update a div within another div element?

<!DOCTYPE html> <html> <head> <title>Business Information Card</title> <script type="text/javascript"> window.onload = init; function init(){ var button = document.getElementById("populate ...

Implementing full-height list elements using CSS

I'm still facing challenges with my lists... After receiving some assistance, I was able to create a horizontal list with perfect dimensions for my needs: each element taking up 33.33% width and adjusting its height based on the tallest element. I ac ...

Creating responsive divs on my webpage

Although I have browsed through various posts with similar questions, none of the solutions seem to work for me. I will make sure to include all relevant information related to my issue and explain why I am unable to resolve it on my own. Currently, I am ...

How come require() doesn't resolve the image path when passed as a prop in NuxtJS?

I am encountering an issue in my NuxtJS project where a component is not displaying an image correctly. Despite passing the image path directly to :src="imageAddress", it does not resolve nor throw an error. I attempted using the path inside requ ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

Control the playback of multiple HTML5 videos with the ability to pause and resume, while also adding a

Trying to achieve the functionality of playing and pausing multiple videos. When one video is played, the others should automatically pause. The videos should appear blurred, except when actively playing. Does this make sense? http://jsfiddle.net/1frjov8e ...

Retrieving the ID and value of a specific dropdown list using jQuery from an array of dropdown lists

My HTML structure looks like this: <?php foreach($active_brand as $brand) { ?> <select name="selector" id="selector"> <?php foreach($options as $option) { ?> <option <?php if($brand['State'] == $option) { ?& ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...