Reputation: 506
I tried to log something after the body element of the page is loaded, but log not appearing in the console. What am I doing wrong?
const body = document.querySelector('body');
function setInitialGradient() {
console.log('Cant see this message on console');
body.style.background = `linear-gradient(to right, ${color1.value}, ${color2.value})`;
cssProperty.textContent = body.style.background + ';';
}
body.addEventListener('load', setInitialGradient);
Upvotes: 5
Views: 21974
Reputation: 6053
The DOMContentLoaded
event will trigger earlier and is usually considered the better option.
[the load event] should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate.
Set it on the document object.
document.addEventListener('DOMContentLoaded', setInitialGradient);
If you must use the load
event, you can add a listener to window
instead:
window.addEventListener('load', setInitialGradient);
But note:
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
Upvotes: 17
Reputation: 85545
load
event is a property of window
neither document
nor body
. You need to use window instead:
window.addEventListener('load', setInitialGradient);
If you want to use function on load of body or any specific html element, then you'll need to use:
body.onload = setInitialGradient;
// I would use document.onload BTW if it is for body rather than other element
Upvotes: 4
Reputation: 378
window.addEventListener('DOMContentLoaded', function() { /*put your code here*/ });
Upvotes: 3