I am just learning JavaScript at the moment and I have been able to write an event handler for when a user clicks on the document that will output the mouse clicks coordinates.
However the problem I am having is that it will only do it once. I thought that if the event handler is waiting for a “click” and if it got one it would evoke the function getCords.
var x = document;
x.addEventListener("click", getCords, false);
function getCords(event){
x.writeln(event.clientX, ",", event.clientY)
}
On MDN:
So, let’s look at
document.write:What does this mean?
It means that your code really looks like this:
The first fix to make (which will also stop the page appearing as “loading” forever) is to add the
document.close()call as advised:Now it’s clearer what’s going on — we’re creating a new document stream here. Your existing document contents are overwritten; the event handler ceases to exist.
In fact, the DOM standard says this explicitly about
open:And your new document doesn’t contain your script, so even re-assigning the event handler inside the callback won’t work.
Best not to use
document.write(anddocument.writeln) at all; assign the text to be the contents of somedivorspannode instead.