1

I have tried every format of doing this, and nothing seems to work, please help!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="script.js"></script>
</head>
<body>
    <button id="btn">Click me</button>
</body>
</html>

JavaScript:

let btn = document.getElementById('btn');

btn.addEventListener('click', func());

function func(){
    alert('hello');
};

The error it returns is:

script.js:3 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at script.js:3:5
SSS
  • 13
  • 3
  • 3
    remove the `()` inside the event listener. So it should be: `btn.addEventListener('click', func)` – zer00ne Jan 15 '22 at 18:32
  • you need to defer the script ` – skara9 Jan 15 '22 at 18:33
  • I just tried that and it returns the same error. - replying to zer00ne – SSS Jan 15 '22 at 18:34
  • works now, thanks! quick question, what is the difference when you defer the script? - replying to skara9 – SSS Jan 15 '22 at 18:36
  • @skara9 please post a detailed answer with explanation – raiyan22 Jan 15 '22 at 18:37
  • 1
    @SSS when you defer the script, it will wait for your html to load before running your js code -- without it, your code runs before the button is loaded into the page, so your `getElementById` won't work – skara9 Jan 15 '22 at 18:37
  • Defer works because the script is loading AFTER the DOM has fully loaded. Since your script is loading in the header, the `btn` element doesn't exist yet, so you are assigning the `let btn` to something that isn't present yet. You could also move your `` before the `

    ` without the `defer` and it would work.

    – disinfor Jan 15 '22 at 18:39

1 Answers1

0

Js script should be executed after template fully loaded

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">Click me</button>
    <script src="script.js"></script>

</body>
</html>
Zrelli Majdi
  • 1,204
  • 2
  • 11
  • 16