I am learning Javascript and when I am testing some features, I found some problems. Here are my codes:
<script>
function onCreate() {
var body = document.getElementsByTagName('body')[0];
body.focus();
body.onkeydown = function(e) {
if (e.keyCode == 32) {
alert(1);
sayHey();
}
}
}
function sayHey() {
document.write("Hey ");
document.write("May");
}, 30);
</script>
</head>
<body onload="onCreate()">
</body>
As you may try, onkeydown event works perfectly when I do not include sayHello() function, which make use of setInterval. When sayHello() is included, when I click space bar, "Hey May" is created which is as expected. However, when I click space bar once more, no alert message and no new "Hey May" is raised. It seems that onkeydown() function do NOT work anymore. Why is it the case?
In addition, when I change document.write(brabrabra)
to the below one, it works.
var newParagraph = document.createElement('p');
var text = "Hey May";
var textNode = document.createTextNode(text);
newParagraph.appendChild(textNode);
body.appendChild(newParagraph);
Why is it the case? Can someone explain to me please? Thanks a lot.
After the document has been parsed, the current document is closed and any use of document.write()
will clear the current document and open a new blank document, thus clearing any event handlers or content you previously had.
So, in your specific example, the first key press triggers your event handler. That shows the alert(1)
and then calls sayHey()
which calls document.write()
which clears the current document and thus your event handler is no longer there. So, for the second press of the space bar there is no event handler in place and nothing happens.
So, if you want to add content to the document after it has been loaded, then you should add the content with something like document.createElement()
and .appendChild()
, not document.write()
.