0

I am following a Traversy Media web tutorial on youtube link in which he creates a modal from scratch, and at minute 17.00 I get an error -

"Uncaught TypeError: Cannot read property 'addEventListener' of null"

Code Snippet

//Get modal element
var modal = document.getElementById('simpleModal');
//Get open modal button
var modalBtn = document.getElementById('modalBtn');
//Get close button
var closeBtn = document.getElementById('closeBtn');


//Listen for click
modalBtn.addEventListener('click', openModal);

//Fucntion to open modal
function openModal() {
  console.log(123);
}
<body>

  <button #id="modalBtn" class="button">Click Here</button>

  <div id="simpleModal" class="modal">
    <div class="modal-content">
      <span class="closeBtn">&times;</span>
      <p>Hello...I am a modal</p>
    </div>
  </div>

  <script src="main.js"></script>
</body>

I would appreciate your help!

Narendra Jadhav
  • 8,799
  • 15
  • 28
  • 38
Gustavs
  • 53
  • 1
  • 8
  • I don't think this question is duplicated as OP did not added the id attribute properly in the HTML and got that error. – Ankit Agarwal Apr 26 '18 at 11:40

2 Answers2

1

This is because you do not have a button (or any element) with id modalBtn in your HTML page due to #id added in place of id. Thus, changing #id in <button #id="modalBtn" class="button">Click Here</button> will fix your error. Javascript will throw an error if it did not find that element in which you are adding a event listener. And #id in attribute do not mean id attribute.

//Get modal element
var modal = document.getElementById('simpleModal');
//Get open modal button
var modalBtn = document.getElementById('modalBtn');
//Get close button
var closeBtn = document.getElementById('closeBtn');


//Listen for click
modalBtn.addEventListener('click', openModal);

//Fucntion to open modal
function openModal(){
console.log(123);
}
<button id="modalBtn" class="button">Click Here</button>

<div id="simpleModal" class="modal">
    <div class="modal-content">
        <span class="closeBtn">&times;</span>
        <p>Hello...I am a modal</p>
    </div>
</div>
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
0
<button #id="modalBtn" class="button">Click Here</button>

Remove character # in the above line and try.

Edit: It should look something like this

<button id="modalBtn" class="button">Click Here</button>