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" onm ousemove="fifa(ev)">onmousemove</div>
CodePudding user response:
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" onm ousemove="fifa(event)">onmousemove</div>
CodePudding user response:
In your HTML just change "ev" to event and it will work.
<div id="div1" onm ousemove="fifa(event)">onmousemove</div>