FurkanO FurkanO - 5 months ago 10
Javascript Question

setting left position in the body of mousemove event listener function doesn't work

I want one of my div's position left value equal to my mousemove event.clientX. Although individual items in my code works by themselves, following code doesnt work. Why ?

var shapeCanvas = document.getElementsByClassName("shape")[0];
shapeCanvas.style.left = '1px'; // works

document.getElementsByClassName("body")[0]
.addEventListener("mousemove",function(e){
shapeCanvas.style.left = e.clientX + "px"; // **doesn't work**
console.log(e.clientX); // works also
},false);

Answer

You were trying to identify the body element by the body class instead of the tag. I added the eventListener to the window instead, for better results. Is this what you were trying to achieve?

var shapeCanvas = document.getElementsByClassName("shape")[0];
shapeCanvas.style.left = '1px';  // works 

window.addEventListener("mousemove",function(e){
   shapeCanvas.style.left = e.clientX + "px"; // **doesn't work**
   console.log(e.clientX); // works also 
},false); 
.shape{
  width:100px;
  height:100px;
  position:absolute;
  background:lightblue;
  }
<div class="shape">

</div>