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

Linda Hamilton
Release: 2024-11-16 09:32:03
Original
392 people have browsed it

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

Determining Click Coordinates on Target Element Using jQuery

To capture the mouse coordinates relative to the target element upon clicking, jQuery offers several methods to obtain accurate results.

event.pageX and event.pageY

The event.pageX and event.pageY properties provide the mouse pointer location relative to the document.

Element.offset()

The offset() method retrieves the element's offset position within the document.

Element.position()

The position() method determines the relative position of an element within its parent container.

Demonstration

Consider the following JavaScript code:

jQuery("#seek-bar").click(function(e) {
    var posX = e.pageX - $(this).offset().left;
    var posY = e.pageY - $(this).offset().top;
    alert("X-coordinate: " + posX + "\nY-coordinate: " + posY);
});
Copy after login

This code will calculate and display the precise click coordinates relative to the target element.

Example HTML

<div>
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template