billy
billy

Reputation: 1493

Trying to get the accurate values of mouse click x and y pos - getting NaN

Trying to identify the relative value of the clicked x and y coordinate and the offsets of the parent container to find the true value where the mouse was clicked on the web page.

The problem is: I am displaying NaN as the x and y on the screen? Not sure why?

// get the position of click
function getPosition(el) {
  var xPosition = 0;
  var yPosition = 0;
 
  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",
  };
}



function handleClick(event) {
    // Return the current element clicked on
    var el = event.currentTarget;
    // Return the offset values of the element clicked on   
    var relOffsetValues = getPosition(el);

    // Get the clicked values that is relative to the element 
    var valuesRelToClickedElementX = event.ClientX;
    var valuesRelToClickedElementY = event.ClientY;

    // Find the true value of x and y by adding the offset and the to clicked value of x and y
    var realValueX = relOffsetValues.x + valuesRelToClickedElementX;
    var realValueY = relOffsetValues.y + valuesRelToClickedElementY;

    // display the x and y of the mouse click
    alert("x:" + realValueX + ", y:" + realValueY);
}

// Set up event handlers according to standards
window.addEventListener("load", function(){
  document.addEventListener("click", handleClick);
});

Upvotes: 0

Views: 532

Answers (1)

Vinod Kumar Kashyap
Vinod Kumar Kashyap

Reputation: 103

2 things need to be corrected to work:

  1. Make event.ClientX to event.clientX and event.ClientY to event.clientY. Notice the small letter in clientX and clientY.
  2. instead of document.addEventListener("click", handleClick); use document.body. addEventListener("click", handleClick);

Vinod

Upvotes: 1

Related Questions