0

I want to add an event manager but, it won't work?

Console shows me

"ReferenceError: event is not defined"

document.getElementsByTagName('div')[0].addEventListener("mousemove", myFunction(event));

function myFunction(event) {
    var x = event.pageX;
    var y = event.pageY;
    var coor = "Coordinates: (" + x + "," + y + ")";
    document.getElementByTagName('p')[0].textContent = coor;
}
<div> 
<p></p>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
PostMaloneM3m3r
  • 113
  • 2
  • 8

2 Answers2

0

When you create an event listener, write the only name of the function:

element.addEventListener("mousemove", myFunction);

document.getElementsByTagName('div')[0].addEventListener("mousemove", myFunction);

function myFunction(event) {
    var x = event.pageX;
    var y = event.pageY;
    var coor = "Coordinates: (" + x + "," + y + ")";
    document.getElementsByTagName('p')[0].textContent = coor;
}
div {
  background-color: red;
  width: 200px;
  height: 200px;
}
<div>
  <p></p>
</div>
Vadym Shashkov
  • 118
  • 2
  • 14
0

While Vadim Shashkov is correct, there is more reasoning behind it. According to documentation put out by Mozilla (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) you are giving the addEventListener function a value instead of a function. You need to give it the function, which is why

document.getElementById('myDiv').addEventListener("mousemove", myFunction);

works.

iHowell
  • 2,263
  • 1
  • 25
  • 49