When a user clicks anywhere on the website, I want to register the mouse x and y pos and want to print it out.
PROBLEM: It prints out 0, 0 positions EVERY time.
this function gets the position of x and y
// get the position of click
function getPosition(el) {
var xPosition = 0;
var yPosition = 0;
while (el) {
if (el.tagName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
yPosition += (el.offsetTop - yScrollPos + el.clientTop);
} else {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPosition,
y: yPosition,
a: "hahah",
};
}
on click event handler
function onClickDo(event) {
var el = event.CurrentTarget;
var posOb = getPosition(el);
for (var key in posOb) {
console.log(key);
}
alert(posOb.x + " x pos");
alert(posOb.y+ " y pos");
alert(posOb.a+ " random string");
}
onload function
window.onload = function() {
document.onclick = onClickDo(event);
};
UPDATE BASED ON ANSWER
// Set up event handlers according to modern standards
window.addEventListener("load", function(){
document.addEventListener("click", handleClick);
});
function handleClick(event) {
var xPosition = 0;
var yPosition = 0;
var el = event.currentTarget; <----------------------- targeting the element not working
while (el) {
if (el.nodeName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
yPosition += (el.offsetTop - yScrollPos + el.clientTop);
} else {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
// return {
// x: xPosition,
// y: yPosition,
// a: "hahah",
// };
alert(xPosition + " x pos" + " and " + yPosition + " y pos");
}
I had to define el
using event.currentTarget
.. however I am getting NaN
error. No SURE. Please help!