Computers & ProgrammingFrontend DevelopmentjQuery

jQuery PageX/Y Event

The jQuery event pageX and pageY provides the position of the mouse pointer, relative to the left edge pageX and/or right edge pageY of the document.

Syntax

event.pageX
event.pageY

Basic Example

In the following jQuery example, the event.pageX and event.pageY will be used to display the X and Y position of the mouse cursor.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(document).mousemove(function (e) {
                $("#pos").text("X: " + e.pageX + " | Y: " + e.pageY);
            });
        });
    </script>
</head>
<body>     
    <div id="pos"></div>
</body>
</html>

You can also get the pageX and pageY coordinates for a specific HTML element by making some simple changes to the jQuery code as follows.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#pos").mousemove(function (e) {
                var x = e.pageX - this.offsetLeft;
                var y = e.pageY - this.offsetTop;
                $("#pos").text("X: " + x + " | Y: " + y);
            });
        });
    </script>
</head>
<body>     
    <div id="pos"></div>
</body>
</html>

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top