Attempting to use addEventListener with closures - similar code works on HTML file without addEventListener

StackOverflow https://stackoverflow.com/questions/22596065

سؤال

I am practicing with some code and I have written some basic code which does work:

    <p>Some paragraph text</p>
<h1>some heading 1 text</h1>
<h2>some heading 2 text</h2>

<a href="#" id="12size">12</a>
<a href="#" id="14size">14</a>
<a href="#" id="16size">16</a>
<script>




function makeSizer(size) {
 return function () {
  document.body.style.fontSize = size + 'px';
};

}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('12size').onclick = size12;
document.getElementById('14size').onclick = size14;
document.getElementById('16size').onclick = size16;


</script>

Now I try a very similar set of code where the JavaScript is not embedded on the html file but is on an external javascript source. I'm trying to use the addEventListener command, but I keep coming back with "TypeError: size12 is null". Here is the code I'm attempting on an external source:

   'use strict'

 function makeSizer(size) {
   return function () {
   document.body.style.fontSize = size + 'px';
   };
  }

  var size12 = document.getElementById('12size');
  var size14 = document.getElementById('14size');
  var size16 = document.getElementById('16size');

  size12.addEventListener("click", makeSizer(12), false);
  size14.addEventListener("click", makeSizer(14), false);
  size16.addEventListener("click", makeSizer(16), false);

Any help on why this addEventListener isn't working would be helpful. Thank you.

هل كانت مفيدة؟

المحلول

It should be noted when I put the same exact code from the HTML file into the .js file, I get this warning in the console: "TypeError: document.getElementById(...) is null"

Since that line of code worked in your original code, the only explanation that seems to fit is that you have moved the <script> element.

Previously you had it after the elements you were trying to getElementById on so they existed in the DOM at the time the script ran. (We can see this in your original code sample)

Now you've moved it somewhere (probably inside the <head>) so it appears before those elements in the document so they haven't been added to the DOM when it runs. (You haven't shown us the new version of the HTML but this is the most likely explanation).

Move the script back.

Alternatively, put your event handle assignment code in a function and run it once all the elements have been added to the DOM (e.g. in response to a load or ready event.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top