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

Spacious width that doesn't require a horizontal scrollbar for navigation

My dilemma is with the width of my body and background image. I set the body width to 1920px to match the background-image for the header. However, since I have a narrower wrapper inside the body, the header background's width gets cut off by the wrap ...

What does AJAX refer to when it comes to managing requests that are still in progress?

Is there a way to display a loading image while an AJAX request is still processing and waiting for a server response? I need a method that can handle the AJAX call until it's complete. jQuery.ajax({ url: "/privileges/users/get-group-use ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...

Glitch Uncovered in Excel Spreadsheet I Exported

I have a situation where I am working with an HTML table that includes both text and radio buttons. The issue arises when I attempt to export the table data along with the selected radio button values to Excel using the 'Export to Excel' button. ...

Ways to configure dynamic and responsive divs using CSS exclusively (no javascript needed)!

I am looking to have my main div expand in height based on the categories div, content, or product pictures. Check out the website here Here are the issues I'm facing: The content div and categories div are both within the main div, but the produ ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

Having trouble with redirecting a website to its appropriate version for mobile or desktop users?

After creating both the desktop and mobile versions of my website, I have a question. How can I determine whether a visitor is using a mobile phone or a PC when they come to my website? Specifically, if a visitor accesses my website through a mobile devic ...

What could be causing me to receive an undefined output when trying to access an array stored within an object

let newData = await tripModel.find( { tripId: ID }, {salesOrder:1, no: "$deliveryDetails.invoiceNo", _id: 0 } ); let nullInvoices = []; console.log("vvvvvvv", newData[0].salesOrder); for (let i = 0; i < newData[0].no.length; i++) ...

What is the correct way to maintain focus on a nested scrolling div over another scrolling div with jQuery?

I have encountered an issue with a modal view that contains content extending beyond its boundaries. To remedy this, I applied the overflow-y: scroll property. However, the problem arises when the modal view overlaps with the body, which also has scrolling ...

When the children within a CSS container are floated, set the height of the container to

I've established a simple layout <div class="container"> <div class="sidebar"> </div> <div class="content"> </div> <div style="clear:both;"></div> </div> where .sidebar and .content ...

Utilize JavaScript to identify the orientation of an iPad device

I have implemented the code below to monitor the orientation of the iPad. However, it seems that this method is only triggered when I physically rotate the device or change its orientation. If the app is launched in landscape mode and I navigate to a dif ...

Can someone explain to me how I can customize the background of a bootstrap container?

Currently, I am working on an EJS login project and I have created a style.css file with the following code: [theme="bloodRed"] { background-color: #ff2424; color: #e571e1; accent-color: #00ff00; } In my register.ejs ...

Scope challenges with making multiple rest calls in Angular.js

As a beginner in Angular.js, I am facing an issue with $scope not receiving additional value from one of two $resource rest calls. Below is the code snippet: controller: function ($scope, $modalInstance, $route) { $scope.server = {} ...

Using the JavaScript JSX syntax, apply the map function to the result of a

My aim is to create a structure resembling the following: <td> {phones.map((phone, j) => <p>{this.renderPhone(phone)}</p> )} </td> However, there may be instances where the phones array is not defined. Is it feas ...

What could be causing my radio button list to stop functioning correctly? (After applying CSS)

While working on a simple postage calculator in Visual Studio with Web Forms (yes, we had to use Web Forms in Class), I included some Bootstrap for styling. However, there was an issue where my RadioButtonList suddenly stopped functioning properly. None ...

Using Angular to display asynchronous data with ngIf and observables

In cases where the data is not ready, I prefer to display a loader without sending multiple requests. To achieve this, I utilize the as operator for request reuse. <div class="loading-overlay" *ngIf="this.indicatorService.loadingIndicators[this?.indic ...

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

Issue with arranging cards in a grid when utilizing v-for alongside bootstrap

Just starting out with vuejs and attempting to create a grid by looping through objects using bootstrap classes. However, I'm running into an issue where the cards are not forming a grid as expected when utilizing the col classes. Below is the code f ...