Atri BasuNeogi
Atri BasuNeogi

Reputation: 13

How can I get mouse location in javascript?

I am working recently with a js game which requires the mouse position to change the background color, I have tried with

event.clientX, event.clientY and event.pageX , event.pageY

and now it had became:-

function l(){
    let x = event.pageX ;
    let y = event.pageY;
    document.bgColor = 'rgb($(x),$(y),$((x/2+y/2))'
};

document.body.addEventListener('mousemove',l());

but ,still it gives error,

uncaught TypeError: Cannot read property 'pageX' of undefined

If anyone solves my problem, a Great Thanks for him in advance Have a good time :-)

Upvotes: 0

Views: 107

Answers (1)

Rafik Farhad
Rafik Farhad

Reputation: 1202

Try this:

var movementFunction = function (event) { 
    console.log(event.pageX, event.pageY);
    let x = event.pageX ;
    let y = event.pageY;
    document.bgColor = `rgb(${x}, ${y}, ${(x/2+y/2)}`
}

document.body.addEventListener('mousemove', movementFunction);


Upvotes: 1

Related Questions