Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side.

https://i.stack.imgur.com/8bpwe.png

Below is the table I am working with -

<tr id="ing-117">
    <td style="width: 15%; vertical-align: middle; display: none;"><img src="arrow-left.png" class="arrow left hidden"></td>
    <td style="width: 70%; text-align: left;" class="txt center lefted"><div class="in"></div>2 cups ice</td>
    <td style="width: 15%; vertical-align: middle;"><img src="arrow-right.png" class="arrow right hidden"></td>
</tr>

Here's my current JavaScript code snippet -

 $('.arrow').unbind('click')
        .bind('click', function(event, is_triggered){
            var th = $(this);
            var x = event.clientX;
            var y = event.clientY;
            console.log(x , y);

When I click on the second <td>, it prints undefined undefined in the console.

Your help will be greatly appreciated. Thank you.

Answer №1

To access the offsetX and offsetY properties from the click event handled, you can use this code:

$('div').click(function(e) {
  var clickX = e.offsetX;
  var clickY = e.offsetY;
  $('span').text(clickX + ', ' + clickY);
});
div {
  width: 150px;
  height: 25px;
  border: 1px solid #000;
  background-color: #EEF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<span></span>


Update

The revised code provided in your query should work effectively (note that it is recommended to use off() and on() instead of unbind() and bind()). Make sure to check the browser console for any possible errors.

 $('.arrow').off('click').on('click', function(e) {
   var th = $(this);
   var x = e.clientX;
   var y = e.clientY;
   console.log(x, y);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="ing-117">
    <td style="width: 15%; vertical-align: middle; display: none;">
      <img src="arrow-left.png" class="arrow left hidden">
    </td>
    <td style="width: 70%; text-align: left;" class="txt center lefted">
      <div class="in"></div>
      2 cups ice
    </td>
    <td style="width: 15%; vertical-align: middle;">
      <img src="arrow-right.png" class="arrow right hidden">
    </td>
  </tr>
</table>

Answer №2

Implement any of the mouse events (mousemove, mouseup, mousedown) and pass the event argument to a function. Within that function, you will be able to retrieve the coordinates by accessing the clientX & clientY properties.

Here's a simple example:

<div onmousemove="displayCoordinates(event)"></div>

function displayCoordinates(event) {
    var x = event.clientX;
    var y = event.clientY;
    var coordinates = "X coords: " + x + ", Y coords: " + y;
}

Answer №3

To achieve this, adjust the td's position by using offset and determine the click position in the window

$(document).on('click','td_selector',function(){
     alert(e.pageX-$(this).offset().left)+"::"+ (e.pageY-$(this).offset().top));
})

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

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Can I restrict access to all routes except one in vue-router? Is this a safe practice? Should I explore alternative methods for achieving this?

I am looking to create an online exam consisting of 5 pages, each with a countdown timer set at 120 seconds and 4 questions on each page. Once the timer runs out, users will be automatically redirected to the next page, or they can manually click the "next ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...

What could be causing my Node.js website to have trouble locating pages in the public directory?

Embarking on my journey in web development using node.js, I encountered an issue while trying to load a particular page, which led to the following error message in my browser: Cannot GET /public/pages/terms-and-conditions.html The file structure is orga ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Maintain the tab order for elements even when they are hidden

Check out this demonstration: http://jsfiddle.net/gLq2b/ <input value="0" /> <input id="test" value="1" /> <input value="2" /> By pressing the TAB key, it will cycle through the inputs in order. If an input is hidden when focused, press ...

display the HTML form when the page is clicked

Trying to implement an onclick method for selecting form types. I have multiple form types available - example here Clicking on one submenu should open up the desired form type directly below the menu How can I dynamically load a form based on the select ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

A guide on integrating mat-select into Angular input fields

I've been trying to implement a mat-select dropdown on my input field, but for some reason, when I click on the arrow, nothing happens and the list doesn't show up. Usually, with autocomplete, when a user starts typing, all the options are displ ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable') ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

Regular expression for selecting characters and numbers in jQuery using a selector

Can someone help me figure out how to select all IDs like this: r1 r2 r3 etc. and not the other IDs like helloWorld I attempted using the CSS selector with jQuery but I'm having trouble understanding how. I tried $('#r[0-9]') but it didn& ...

Eliminate the empty gap preceding the slideshow

I have a slideshow and aside content in HTML. My goal is to eliminate the space below the slideshow so that the aside content can be positioned right next to the end of the slideshow. Unfortunately, I am unsure how to remove this space without disrupting ...

Guide for showing an alert message after submitting a form using PHP and jQuery

Everything seems to work well with the jQuery modal, but I'm struggling to figure out how to display an alert message when the form is successfully executed by PHP. $.post( 'name.php', { ime: ime, location: location }, functio ...

Every time I adjust the browser height on my landing page, the elements start to overlap each other

Something strange is happening - as I shorten the height of the browser, elements on the page start to overlap. I've tried using Firebug to troubleshoot, but haven't had any luck so far. Maybe someone here can help me out! EDIT: It seems that e ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...