How to call jQuery Event Method inside another jQuery Event Method?

I have written jQuery codes which specifies a function named "checkPage" to be executed when the DOM is fully loaded. The "checkPage" function will return the position of the mouse pointer, relative to the edge of the document. However, the "checkPage" function is not returning the position of the mouse pointer, relative to the edge of the document. Can anyone please tell me what is wrong with my codes? Your help will be appreciated :)

Here are the jQuery codes:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            checkPage();
        });

        function checkPage(event) {
            $("span").text("X: " + event.pageX + ", Y: " + event.pageY);
        }
    </script>
</head>
<body>
    <p>The mouse pointer position is at: <span></span></p>
    <p>This is a paragraph.</p>
</body>
</html>

Upvotes: 0

Views: 46

Answers (2)

Carlo
Carlo

Reputation: 2112

the event variable is passed from a listener, in this case when yo call the checkPage(); you don't pass anything as a parameter. Try for example to listen to a mouse even:

$('body').on('click', checkPage);

In this case when the click happens jquery will call your function with the event argument set.

Upvotes: 0

Satpal
Satpal

Reputation: 133453

As of now you are only invoking checkPage() function at document-ready handler. Never after that. You need to bind mousemove event.

$(document).ready(function() {
  $(document).on('mousemove', checkPage);
});

function checkPage(event) {
  $("span").text("X: " + event.pageX + ", Y: " + event.pageY);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<p>The mouse pointer position is at: <span></span>
</p>
<p>This is a paragraph.</p>

Upvotes: 1

Related Questions