Jacob
Jacob

Reputation: 25

Javascript produces error on event.clientX

The program that I am building is a program that when the mouse is down, it reads mouse X and mouse Y positions. The code that produces the error is below:

function updateLocation(event) {
    setTimeout(function(event){
        var X = event.clientX;
        var Y = event.clientY;
    },300);
}

chrome, opera, firefox, and edge all say "Uncaught TypeError: Cannot read property 'clientX' of undefined(…)" what I don't understand is even if I copied the source code for event.clientX from w3schools.com, It still produces that error. I have tried rewriting the code, I have tried only passing event to setTimeout() or only to the function, but nothing works. can someon please help me, it's getting frustrating.

Here is a list of all the things that I tried:

function updateLocation(event) {
    setTimeout(function(){
        var X = event.clientX;
        var Y = event.clientY;
    },300);
}

function updateLocation() {
    setTimeout(function(event){
        var X = event.clientX;
        var Y = event.clientY;
    },300);
}

function updateLocation(event) {
    alert(event.clientX);
}

function updateLocation(event) {
    setTimeout(function(event){
        var X = event.windowX;
        var Y = event.windowY;
    },300);
}

function updateLocation(event) {
    setTimeout(function(){
        var X = event.windowX;
        var Y = event.windowY;
    },300);
}

function updateLocation() {
    setTimeout(function(event){
        var X = event.windowX;
        var Y = event.windowY;
    },300);
}

Upvotes: 0

Views: 1134

Answers (1)

Aruna
Aruna

Reputation: 12022

setTimeout callback function should not be having any argument since no parameters will be passed when it gets fired. That's why its getting as undefined.

If you just remove it from the function as below, it will work as you expected.

You can have a look at the below code.

function updateLocation(event) {
    setTimeout(function(){
        var X = event.clientX;
        var Y = event.clientY;
      console.log(X + ', ' + Y);
    },300);
}
.container {
  background-color: gray;
  width: 500px;
  height: 500px;
}
<div class="container" onmousedown="updateLocation(event)">Test Div</div>

Upvotes: 1

Related Questions