jQuery event.pageX Property



The jQuery event.pageX property is used to find the horizontal position of the mouse pointer, relative to the left edge of the document.

This jQuery property provides the X-coordinates of the mouse pointer when an event such as: click, mousemove, etc events are triggered.

Syntax

Following is the syntax of the jQuery event.pageX property −

event.pageX

Parameters

This property does not accept any parameter.

Return Value

This property returns the horizontal position of the mouse pointer.

Example 1

The following is the basic example of the jQuery event.pageX property −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Click the mouse pointer relative to the left edge of the document</p>
    <p>Mouse pointer x coordinate: <span></span></p>
    <script>
        $(document).click(function(){
            $('span').text(event.pageX);
        })
    </script>
</body>
</html>

Output

The above program returns the X-coordinates of the mouse pointer when clicked, relative to the left edge of the document as −


Example 2

Following is another example of using the jQuery event.pageX property. We use this property to find the X-coordinates of mouse pointer for a specific area −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        div{
            width: 300px;
            height: 300px;
            background-color: green;
        }
    </style>
</head>
<body>
    <p>Move the mouse pointer relative to the left edge in the below box</p>
    <p>Mouse pointer x coordinate: <span></span></p>
    <div>

    </div>
    <script>
        $('div').mousemove(function(){
            $('span').text(event.pageX);
        })
    </script>
</body>
</html>

Output

After executing the above program, a box with a green background is displayed. When the mouse pointer moves within the box, the X-coordinates will be displayed as −


Example 3

Let's combine both event.pageX and event.pageY properties to simultaneously find the X and Y coordinates, which represent the position of the mouse pointer −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Move the mouse pointer on your browser screen</p>
    <p>X coordinate: Y coordinates <span></span></p>
    <div>

    </div>
    <script>
        $(document).mousemove(function(){
            $x = event.pageX;
            $y = event.pageY;
            $('span').text($x + " : " + $y);
        })
    </script>
</body>
</html>

Output

When the mouse pointer moves over the browser screen, the X and Y coordinates will be displayed on the screen as −


jquery_ref_events.htm
Advertisements