Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas?

Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html

They provide this code snippet:

function initializeMouse() {
  canvasMinimumX = $("#canvas").offset().left;
  canvasMaximumX = canvasMinX + WIDTH;
}

function handleMouseMove(event) {
  if (event.pageX > canvasMinimumX && event.pageX < canvasMaximumX) { // How do you access canvasMinimumX outside of its scope?
// Also, what is pageX? Is it the mouse coordinate? If not, how can I obtain it?
    paddleLocationX = event.pageX - canvasMinimumX;
  }
}

$(document).mousemove(handleMouseMove);

And lastly, I want this action to occur on mouse click. So, I write:

$(document).click(onMouseClick)

Is that correct?

Answer №1

For those looking for a comprehensive guide on implementing it with JS, this resource is highly recommended: JavaScript Capture Mouse X-Y Position Script - Quick-Take Mini-Tutorial

Answer №2

Give this a shot for better results.

    $("#clickDiv").on("click", function (event) {
            var xPosition = $(this).position().left;
            var yPosition = $(this).position().top;
            var cursorXPos = (event.pageX - xPosition);
            var cursorYPos = (event.pageY - yPosition);
            //cursorXPos, cursorYPos represent the precise mouse pointer location
});

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

Can you attach a jQuery function to multiple CSS selectors at once?

Is it feasible to bind a mouseout call to two CSS selectors in order to trigger another action when the mouse moves away from both elements simultaneously? ...

Looking to update a specific element in an array on an hourly basis?

var temperature = [-18 , -18.1 , -18.2, -18.3, -18.4, -18.5, -18.6, -18.7,-18.8, -18.9, -19 , -19.1 , -19.2, -19.3, -19.4, -19.5, -19.6, -19.7,-19.8, -19.9, -20]; $(".warlotemp").html(temperature[0]); $(".warlotemp").append(" C"); I am intere ...

How to build custom middleware with parameters in Node.js

I'm working on creating a middleware in nodejs for access levels, and I've written the following middleware: class AccessUser extends middlware { async AccessUser(access,req, res, next) { const getTokenFrom = (req) => { const autho ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Determine whether either of these elements has the mouse hovering over it using jQuery

In my DOM, I have two separate elements that need to change when either one is hovered over. If the link is hovered over, not only does the image src need to change (which is easy), but also the link color needs to change. Similarly, if the image is hovere ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...

Seeking a more deliberate option instead of using $(window).load, one that is not as quick as $(document)

Currently, my goal is to utilize JavaScript to conceal my preloader once the DOM and key elements have been loaded. The issue lies in the fact that various iframes on my page can significantly slow down this process. It seems that using jQuery's $(do ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

Difficulty encountered when attempting to extract a username with multiple spaces using the .split() method in Discord.js with NodeJS

Currently, I am enhancing a feature in my Discord Bot that fetches the League of Legends statistics of a player by using the command !lolid [enter_username_here] in a Discord chat room. The function works smoothly for usernames with just one word; however, ...

Obtain an array of images from the Google Places API through a nearby search functionality

Utilizing the Google Places API within a JSP to retrieve JSON data in JavaScript has been successful, except for one aspect - the photos. Despite using the nearbySearch function, the PlacePhoto object is not populating as expected. Here is the nearbySearc ...

Updating template views in Grails without the use of ajax enables seamless and dynamic

In my GSP template, I am looking to provide the user with updates on the progress of a task within an overlay. Once the user submits their data, the controller triggers a service to carry out the task. Simultaneously, another service calculates the percen ...

Can someone provide guidance on how to validate a HEX color in Cypress?

As I dive into testing with Cypress, my lack of experience has become apparent. I am trying to test the background-color CSS property on a specific element, but running into an issue - everything is in RGB format behind the scenes, while I need to work wit ...

What is the efficient way to toggle localStorage based on checkbox selection using jquery?

I am looking to efficiently manage localStorage using checkboxes. When a checkbox is checked, I want to add the corresponding value to localStorage, and remove it when unchecked. var selectedModes = new Array(); $('.play_mode').on('click& ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

Tips for manipulating bits 52-32 within Javascript code, without utilizing string methods

Here is my functional prototype code that is currently operational: function int2str(int, bits) { const str = int.toString(2); var ret = ''; for (var i = 0; i < (bits - str.length); ++i) { ret += '0'; } re ...

Connecting a pre-existing Angular 2 application to a Node.js server: A step-by-step guide

I am currently working on an Angular 2 application with the following structure : View Structure of my Angular app Furthermore, on the server side : View Structure of server app I have noticed that there are two module dependencies folders, but I am un ...

I am looking to create an extension that can automatically paste text from a variety of lists, but unfortunately, I am struggling to get it up and running correctly

I'm having trouble pasting text into text boxes or documents. I've tried various methods, but nothing seems to work. Am I missing something? Is there a solution or could I get some assistance? manifest.json { "manifest_version": 3, ...