eow2898 eow2898 - 2 months ago 13
Javascript Question

How to test whether horizontal mouse position is equal to a variable in Javascript

I'm working on a javascript learning project (no jQuery) and I need to test whether the horzontal position of the mouse is the same value as a variable.

I have a div that follows the mouse around, and when its horizontal position is equal to that of another div, I want to do something.

Here's what I've got:

var x = e.clientX;

var otherVar = 200;

document.getElementById('testDiv').style.left = otherVar + "px";

if (x == otherVar) {

//do stuff

} else {

//do other stuff

}


I've tested it and it doesnt seem to work, however there are no errors showing up on the console.

I appreciate your help.

Answer

document.getElementById expects a string and you need to listen for the mousemove event:

This should help point you in the right direction. Good luck.

//define your vars:
var otherDiv = document.getElementById("otherDiv"),
    testDiv = document.getElementById("testDiv"),
    otherVar = otherDiv.offsetLeft; //otherDiv's left position in px
//add event listener:
document.addEventListener("mousemove", onmousemove);
//handle the event:
function onmousemove(e) {
  var x = e.clientX; //get the current x position
  testDiv.style.left = x + "px"; //move testDiv
  if (x >= otherVar) {
    //do stuff
    testDiv.style.backgroundColor = "green";
  } else {
    //do other stuff
    testDiv.style.backgroundColor = "red";
  }
};
body {
  margin:0;
  background: #eee;
}
#otherDiv {
  position: relative;
  margin-left: 30%;
  width: 70%;
  height: 20px;
  background-color: blue;
}
#testDiv {
  position: absolute;
  left: 0;
  top: 20px;
  width: 100px;
  height: 100px;
  background-color: red;
}
<div id="otherDiv">otherDiv</div>
<div id="testDiv">testDiv</div>