Home › Forums › JavaScript › clientX not working with mousemove event in JS
- This topic is empty.
-
AuthorPosts
-
April 18, 2018 at 12:41 am #269959PranabParticipant
Trying to get the values of clientX and clientY with mousemove event but nothing popped in screen.
Heres’s the code –
HTML
X value =
Y value =
JS
let xpart = document.querySelector(".x span"), ypart = document.querySelector(".y span"); function screenView(e){ xpart.innerHTML = e.clientX; } window.addEventListener("mousemove", screenView(event));
What did i do wrong? Please help me out anyone…
April 18, 2018 at 1:30 am #269960ShikkedielParticipantI think you’ll have to write it like this if you want to pass that event parameter:
window.addEventListener("mousemove", function(event) { screenView(event); });
April 18, 2018 at 5:00 am #269961PranabParticipantOhh ok… Thanks buddy. Now i got it.
If i simple put this function over there, then it would render like this –
xpart.innerHTML = e.clientX
and now because of e, it return undefined.but if i first mentioned function(event) and then the callback, then
e
replaced withevent
.and Boom!! that’s it. Thanks again…
April 18, 2018 at 12:45 pm #269983PoganyParticipantAlso you can write it like this:
window.addEventListener("mousemove", screenView);
April 18, 2018 at 2:33 pm #269987PranabParticipantYes, you’re right. I never thought of it but for that i’ve to replace the callback
e
toevent
then it’s working…nice idea… ThanksApril 18, 2018 at 2:38 pm #269988PranabParticipant@Shikkediel and @Pogany what is e in e.clientX? I just changed it with random variables or changed it to my name and still working, still showing me the co-ordinates. what is the parameter refering to?
April 18, 2018 at 6:56 pm #270021ShikkedielParticipantIt’s referring to the event itself – which is an object, looking a bit like this (doesn’t matter what you name it):
event = { clientX: 733, // coordinate value in px clientY: 137, target: html, // item from which event originated type: "click" // kind of event }
And a whole bunch more data… have a look here, open the console, then click the window – you can see the entire object:
If you want to access the values, you do this by referring to the key as a dot notation:
var whatever = event.type; // whatever == "click";
Or with this notation:
var whatever = event['type'];
So the object has keys and those are coupled with the values (which is what you’re after).
April 19, 2018 at 9:27 am #270037ShikkedielParticipantBy the way, it matters a tiny bit what you name it because some words are reserved in JS.
And I’d advise to not try logging the
mousemove
to the console because it fires with each cycle of your computer, which can amount to more than 100 events a second… -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.