0
var box=document.getElementById("box");
var display=document.getElementById("display");/*to display clientX result*/
var x=box.clientX;

box.addEventListener("click", show);

function show(){
    display.innerHTML=x;
}

I feek like there is something simple going over my head that I just cant see

TheGarry243
  • 63
  • 1
  • 7
  • Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/)). – T.J. Crowder May 17 '19 at 15:10
  • What is the expected behavior? showing the `box`'s `x` clicked position on `display`? – briosheje May 17 '19 at 15:11

2 Answers2

0

The properties are clientLeft and clientTop, not clientX and clientY. See the Element interface. So

var x=box.clientLeft;
// -------------^^^^

Separately, and this may or may not be a problem depending on what you're doing, the line

var x=box.clientX;

gets the value of clientX from box as of when it runs, and then stores that value. There's no ongoing connection between x and box.clientX. So when the click occurs later and show is called, it shows the value as of earlier, when var x=box.clientX; ran. Depending on when that is, even if you make it clientLeft, you may get 0 instead of a valid value (if you're reading it during the initial loading of the page, and so the page may not have been laid out yet). Again, depending on what you're doing, you may want to wait and look up box.clientLeft when the click occurs. E.g.:

var box = document.getElementById("box");
var display = document.getElementById("display");

box.addEventListener("click", show);

function show(){
    display.innerHTML = box.clientLeft;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Maybe he thinks that `box.clientX` holds the MouseEvent's `clientX` property upon the click event on `box`? that's the only reasonable guess, to me. – briosheje May 17 '19 at 15:13
  • @briosheje - Hard to say, it could go either way, though I tend to think it's just a simple naming error. Maybe worth your posting an answer in case that's what the OP meant? – T.J. Crowder May 17 '19 at 15:15
  • 1
    Nah, let's see if that's what he needs, it was just to add something to your answer, which is already complete and likely what the user is looking for. I'm just wondering how he came up with `clientX` instead of `clientLeft` :P – briosheje May 17 '19 at 15:17
  • @briosheje :-) Easy mistake to make. – T.J. Crowder May 17 '19 at 15:18
0

If you want to get the x-position of the mouse-click inside the box-element, you can achieve this with the help of the properties provided by the click-event.

let box = document.getElementById("box");
let display = document.getElementById("display");

function showMouseX(event){
    display.innerHTML = event.clientX;
}

box.addEventListener("click", showMouseX);
Jan
  • 2,853
  • 2
  • 21
  • 26