Nurdaulet Shamilov
Nurdaulet Shamilov

Reputation: 506

Why "load event not working on addEventListener()"?

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

Answers (3)

Graeme Stuart
Graeme Stuart

Reputation: 6053

Use DOMContentLoaded instead

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

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

Bhojendra Rauniyar
Bhojendra Rauniyar

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

burg.developer
burg.developer

Reputation: 378

window.addEventListener('DOMContentLoaded', function() { /*put your code here*/ });

Upvotes: 3

Related Questions