2
If I put the code free, without being inside the onload
, the variable button
flipped null
. My current code works, but I wanted to know why it doesn’t work without being inside the function onload
.
HTML
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./script.js"></script>
</head>
<body>
<h1 id="title">Title</h1>
<input id="start" type="submit" value="Start">
</body>
</html>
Javascript
onload = function() {
let h1 = document.getElementById("title");
let button = document.getElementById("start");
button.addEventListener("click", changeTitleText);
function changeTitleText() {
h1.innerHTML = "New Title"
}
}
It’s not just after
load
. In fact, it works because theload
will always be fired afterDOMContentLoaded
, which is the event that marks, in fact, the moment when the GIFT can be manipulated.– Luiz Felipe