0

document.addEventListener('load', () => {
    console.log('hi')}
)
h1, h2{
    color:white;
    text-align: center;
    font-weight: 300;
}
body{
    background-color: rgb(24, 24, 24);
    overflow-x :hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel = "stylesheet" href = "style.css">
    <script src = "script.js"></script>
    <title>Test</title>
</head>
<body>
        <h1 style="font-size: 50px;" id = "hi">Hi</h1>
</body>
</html>

(By the way, this isn't the full code. It is just some placeholder stuff.)

As you can see from the snippet, the 'hi' doesn't appear in the console.log. Any ideas why?

jkimishere
  • 127
  • 1
  • 7

2 Answers2

5

There is no load event fired on the document object.

You could use a DOMContentLoaded event or listen for a load event on the window object.

Note that they fire at different times, so make sure you read the documentation to understand which is right for you.


You might also wish to remove the event listener entirely and use a defer attribute to delay script execution instead.

This would delay script execution until after the DOM was ready (which is probably why you are trying to use an event handler here) while also allowing the script to download in parallel with the HTML being parsed (which is a slight performance enhancement).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Okay, I have another problem now, the js isn't listening to a document.addEventListener('scroll,', function(){}. Any ideas why? – jkimishere Jun 08 '22 at 12:49
  • @jkimishere — If you have a new question, [ask a new question](https://stackoverflow.com/questions/ask) (and include a [mcve]). – Quentin Jun 08 '22 at 12:50
3

You are listening to the wrong event. E.g.

  document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });

Read more here: https://developer.mozilla.org/de/docs/Web/API/Window/DOMContentLoaded_event

TheLegend27
  • 73
  • 1
  • 10