Let's look at the script in two sections. First, the code that logs the coordinates to the screen. This code will be called by the event handler for the various mouse events we watch.
Displaying the coordinates
As we'll see in the HTML, the inner box (the one we're watching for events on) contains several paragraphs; one for each of the four coordinate systems we'll be reporting on.
let inner = document.querySelector(".inner");
let log = document.querySelector(".log");
function setCoords(e, type) {
const idX = `${type}X`;
const idY = `${type}Y`;
document.getElementById(idX).innerText = e[idX];
document.getElementById(idY).innerText = e[idY];
}
A reference to the <div>
inside the inner box which contains the paragraphs that will show the coordinate information is fetched into log
.
The setCoords()
function is designed to accept as input a MouseEvent
and the name of the origin to use when obtaining the coordinates. The implementation is then quite simple. The variables idX
and idY
are set to strings with the names of the properties corresponding to the coordinates in the given coordinate system. For example, if the value of type
is "page"
, then idX
is "pageX"
and idY
is "pageY"
.
Handling the mouse events
setCoords()
is called by the event handler for the various mouse events, named update()
; this is shown below.
function update(e) {
setCoords(e, "offset");
setCoords(e, "client");
setCoords(e, "page");
setCoords(e, "screen");
}
inner.addEventListener("mouseenter", update, false);
inner.addEventListener("mousemove", update, false);
inner.addEventListener("mouseleave", update, false);
The event handler is in the update()
method. It calls setCoords()
once for each coordinate system, passing in the event that occurred.
Our main code sets up the event handlers on the inner box by calling addEventListener()
for each of the types mouseenter
, mousemove
, and mouseleave
.