How can I retrieve the mouse click coordinates on an image using JavaScript?

Currently facing an issue with the code provided below for retrieving x/y coordinates in JavaScript.

I am working on creating a color picker using an image. The objective is to display a color window and cancel button when a user clicks on the pick color button. Then, upon clicking on the image, I need to determine the x/y coordinates to specify the selected color.

The problem lies in the fact that the alerts are not functioning properly.

alert(e.clientX - offsetl);
alert(e.clientY - offsett);

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
    display: none;
    opacity: .8;
    position: fixed;
    top: 0px;
    left: 0px;
    background: #FFF;
    width: 100%;
    z-index: 10;
}
#dialogbox{
    display:none;
    position: fixed;
    background: #f2f2f2;
    border-radius:5px; 
    z-index: 10;
}
#dialogboxhead{background:white;height:40px;margin:10px;}
#text {float:left; text-align:center;margin:10px; font-size:19px;}
#cancel{float:left;margin:9px;}
#image{
    margin-top:0px;
    padding:10px;
}
</style>

<script type="text/javascript">
function CustomAlert(){
    this.render = function(dialog){
        var winW = window.innerWidth;
        var winH = window.innerHeight;
        var dialogoverlay = document.getElementById('dialogoverlay');
        var dialogbox = document.getElementById('dialogbox');
        dialogoverlay.style.display = "block";
        dialogoverlay.style.height = winH+"px";
        dialogbox.style.left = (winW/2) - (550 * .5)+"px";
        dialogbox.style.top = "100px";
        dialogbox.style.display = "block";
    }
    this.cancel = function(){
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dialogoverlay').style.display = "none";
    }
}
var Alert = new CustomAlert();
function position(e){
    var offsetl = document.getElementById('image').offsetLeft;
    var offsett = document.getElementById('image').offsetTop; 
    alert(offsetl);
    alert(offsett);
    alert(e.clientX - offsetl);
    alert(e.clientY - offsett);
}
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
    <div id="dialogboxhead">
     <p id="text">Select color</p>
     <input type="button" onClick="Alert.cancel()" id="cancel" name="Cancel" value="Cancel"/>
    </div>
    <div>
    <img id="image" src="color.png" onClick="position()"/>
    </div>
</div>
<button onclick="Alert.render('Hello World');" >pick color </button>
</body>
</html>

Answer №1

If you're looking to track mouse position with JavaScript, jQuery is a great tool to use. By attaching a click event handler to your image element, you can easily retrieve the x and y coordinates of the mouse cursor. Here's an example of how you can achieve this:

$(document).ready(function () {
    $('img#image').click(getMousePosition);
});

function getMousePosition(e) {
    var mouseX = e.pageX,
        mouseY = e.page;
}

You can test out this functionality in JSFiddle by following this link: http://jsfiddle.net/zV3dH/.

I hope this solution works for you!

Answer №2

Give this code a try, my friend. I guarantee it will function as intended.


function determineMousePosition(event) {
     return {x:event.clientX, y:event.clientY};
}

You can implement it in the following manner:


document.querySelector("#image").onclick = function(event) {
    var position = determineMousePosition(event);
    alert(position.x);
};

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

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Issues with Google charts loading may arise on ajax calls

Recently, I have been experimenting with incorporating Google Charts into my website to showcase data from Google Analytics. To enhance user experience, I decided to split my analytics reports into distinct sections such as Pages, Browsers, Operating Syst ...

Issue with HTML 5 offline storage cache manifest on mobile devices

I have developed a mobile web app and I would like to be able to use it offline as well. I have tried using a manifest file and it works fine with desktop browsers, but unfortunately not with mobile browsers. Can anyone help me identify the issue? Thank ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Problem with using React state hook

Trying to implement the state hook for material-ui's onChange feature to manage error texts, I encountered an issue. I have included a screenshot of the error displayed in the console. https://i.sstatic.net/qjed8.png Below is the snippet of my code: ...

Updating tooltip text for checkbox dynamically in Angular 6

Can anyone help me with this code? I am trying to display different text in a tooltip based on whether a checkbox is active or not. For example, I want it to show "active" when the checkbox is active and "disactive" when it's inactive. Any suggestions ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result. var characters = ['Iron Man', ...

Is there a way to match a compressed javascript stack trace with a source map to pinpoint the correct error message?

When managing our production server, I have implemented minified javascript without including a map file to prevent users from easily deciphering errors. To handle angular exceptions caught by $exceptionHandler, I developed a logging service that forwards ...

Execute the ajax function using Facebook API

I am currently working on a code to fetch data from Facebook to my localhost, but I have encountered some challenges along the way. Here are the issues that I am facing and I would appreciate any assistance: (1) Initially, I am retrieving data from a spec ...

Steer clear of directly accessing views in AngularJS using angular-ui-router

In my AngularJS App setup, I have the following configuration: angular .module('MyApp') .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvi ...

Generating Unique Random Numbers with JavaScript

Is there a way to generate 5 unique random lottery numbers using JavaScript? I've been working on the code below, but can't seem to figure out how to ensure there are no duplicate numbers in the final selection. I tried adding conditionals and lo ...

Background Image Will Not Expand

After searching for a solution on how to stretch the background image in HTML for this specific section of my website, I came across this code. However, despite implementing it, the desired effect is not being achieved. Can anyone spot what mistake I may ...

Disable the default controls on the Open Layers Bing Map

I am currently working on an App that utilizes Geolocation with Open Layers to load a Bing Map Layer. My goal is to enable touch-based zooming and remove the default zoom buttons. Additionally, I would like to relocate the 'i' button to prevent a ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Animating shakes with AngularJS

As I continue learning AngularJS, I find myself transitioning from using jQuery to achieve similar functionality. One specific challenge I'm facing involves my login function: it currently redirects a user upon successful login, but only prints to the ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...