I'm brushing up on my Javascript after not using it for many years. I'm using the book "Secrets of the JavaScript Ninja, Second Edition" and the first sample code in the book looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Web app lifecycle</title>
<style>
#first {
color: green;
}
#second {
color: red;
}
</style>
</head>
<body>
<ul id="first"></ul>
<script>
function addMessage(element, message) {
var messageElement = document.createElement("li");
messageElement.textContent = message;
element.appendChild(messageElement);
}
var first = document.getElementById("first");
addMessage(first, "Page loading");
</script>
<ul id="second"></ul>
<script>
document.body.addEventListener("mousemove", function() {
var second = document.getElementById("second");
addMessage(second, "Event: mousemove");
});
document.body.addEventListener("click", function() {
var second = document.getElementById("second");
addMessage(second, "Event: click");
});
</script>
</body>
</html>
and it works as expected in that when you load the page you see the text in green "Page loading" then as you move the mouse or click you see the text "Event: mousemove" or "Event: click" depending.
What happend though is when I typed the code initially, I typed it like below:
<!DOCTYPE html>
<html>
<head>
<title>Web app lifecycle</title>
<style>
#first {
color: green;
}
#second {
color: red;
}
</style>
</head>
<body>
<ul id="first"></ul>
<script>
function addMessage(element, message) {
var messageElement = document.createElement("li");
messageElement.textContent = message;
element.appendChild(messageElement);
}
</script>
<ul id="second"></ul>
<script>
document.body.addEventListener("mousemove", function() {
var second = document.getElementById("second");
addMessage(second, "Event: mousemove");
});
document.body.addEventListener("click", function() {
var second = document.getElementById("second");
addMessage(second, "Event: click");
});
</script>
</body>
</html>
I left out the
var first = document.getElementById("first");
addMessage(first, "Page loading");
and without this code the page is blank. Nothing happens when I move the mouse or click. What I was expecting was that the "Page loading" text will not display but the "Event: mousemove" and "Event: click" would display when they occur.
Can someone explain what is happening here?
2 Answers 2
The reason why you are not seeing the events is because the event listener is being added to document.body. Since there are no elements in the body, it's height is 0 and the element can't be hovered over or clicked on. If you instead add the event listener to the window the events will fire regardless of the location of the mouse.
window.addEventListener("mousemove", function() { ... });
window.addEventListener("click", function() { ... });
1 Comment
<ul id="second"></ul> a height / width in css.You actually do not have any area on which the events (mousemove, click) could be executed. Try setting the html an body height:
html,
body {
height: 100%;
}