I am learning about events in JavaScript, following the official documentation, where the first example is: HTML:
<button>Change color</button>
JS:
const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.onclick = function() {
console.log("Oprimieron el boton");
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
The previous code does not work unless you use an event for when the DOM is loaded completely, the error is: DOM.HTML: 11 Uncaught Typeerror: Cannot Set Properties of Null (setting 'onclick') (my JS file is called Dom). Investigating I found that it may be because the DOM has not been generated when the script declares and uses the constant obtained by the Dom button. To fix the error use: window.onload = function () { } Inside her I put the example code, the error is solved, the question is, must I always make sure with some function that the DOM will be completed for then executing the JS code?