0

In this example, when I move mouse inside a div, I want to show the (x and y co-ordinates) of mouse current position, but it is showing error. Why?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
<div id="div1" onmousemove="fifa(ev)">onmousemove</div>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • See https://stackoverflow.com/a/63119431/1169519 , what causes the error is explained in Often misunderstood behavior chapter. – Teemu Feb 07 '22 at 06:42

2 Answers2

2

Your error is you are trying to pass the unknown variable ev - it does not exist. You can pass (event) as they do at the site you used: myFunction(event)

I strongly recommend to change to eventListener and also to use MDN over w3schools

const div1 = document.getElementById('div1'); // cache the element
// only change colour once, using class
div1.addEventListener("mouseenter", function(e) {
  this.classList.add("silk")
})
div1.addEventListener("mouseleave", function(e) {
  this.classList.remove("silk")
})

div1.addEventListener("mousemove", function(e) {
  this.innerHTML = (e.clientX + " "  + e.clientY);
})
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
div.silk {background:cornsilk; }
<div id="div1">onmousemove</div>

For your information but please use my version, here is a fixed version of your code.

Note I pass the event to the function and it is picked up as ev - not recommended since it is already available IN the function

function fifa(ev){ // event passed as ev
  ev.target.style.background = "cornsilk"; // the div is the event target
  ev.target.innerHTML = (ev.clientX + " "  + ev.clientY); 
}
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
<div id="div1" onmousemove="fifa(event)">onmousemove</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

In your HTML just change "ev" to event and it will work.

   <div id="div1" onmousemove="fifa(event)">onmousemove</div>
Shariq Ansari
  • 3,941
  • 1
  • 27
  • 30