The problem appears to be that the global symbol clear
is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah
), it works just fine:
Version using clear
which fails:
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
Version using blah
which works:
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this. Now that JavaScript modules are supported in all major environments, you can use those to avoid creating globals and possibly conflicting with them: Top-level declarations in modules aren't globals, they only have module scope (similar to the old way of doing this where you'd wrap all your code in an inline-invoked function).
A corollary to that is to not use old-style onxyz=...
attributes to hook up event handlers, because they require globals. Instead, hook things up with code:
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="module">
// Top-level declarations in modules aren't globals, so this
// `clear` doesn't conflict with the global `clear`
const header = document.getElementById("the-header");
header.addEventListener("mouseover", function() {
go("The dog is in its shed");
});
header.addEventListener("mouseout", clear);
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
</script>
clear
refers todocument.clear
: developer.mozilla.org/en-US/docs/Web/API/document.clear – Loquacity