Home >Web Front-end >CSS Tutorial >How to Get Precise Click Coordinates Relative to a Target Element in jQuery?

How to Get Precise Click Coordinates Relative to a Target Element in jQuery?

DDD
DDDOriginal
2024-11-15 07:47:02307browse

How to Get Precise Click Coordinates Relative to a Target Element in jQuery?

Finding Click Coordinates on Target Element Using jQuery

In order to obtain the precise position of a mouse click on a specific target element, you may consider utilizing either the pageX and pageY properties to determine the position relative to the entire document, or the offset() method to establish the relative position within the specific element.

However, if you require the relative position within the element's parent or another containing element, you may employ the position() method. Here's an example demonstrating the usage of these methods:

$('#element').on('click', function(e) {
  // Determining position relative to document using pageX and pageY:
  var clickX = e.pageX;
  var clickY = e.pageY;

  // Determining position relative to element using offset():
  var offsetX = $(this).offset().left;
  var offsetY = $(this).offset().top;
  var relativeClickX = e.pageX - offsetX;
  var relativeClickY = e.pageY - offsetY;

  // Determining position relative to parent using position():
  var positionX = $(this).position().left;
  var positionY = $(this).position().top;
  var parentRelativeClickX = e.pageX - positionX;
  var parentRelativeClickY = e.pageY - positionY;
});

In the case of your code:

jQuery("#seek-bar").click(function(e){
    var x = e.pageX - e.target.offsetLeft;
    alert(x);    
});

Your intention is to retrieve the position of the mouse cursor relative to the #seek-bar element upon clicking. However, the subtraction of e.target.offsetLeft is incorrect because the offsetLeft property returns the position of the element relative to its parent. Instead, you should utilize e.pageX directly, which provides the x-coordinate relative to the document.

Refer to the provided code demonstration for a more detailed elaboration.

The above is the detailed content of How to Get Precise Click Coordinates Relative to a Target Element in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn