2

I have written a self-invoking JavaScript code:

(function assignment12_3() {
    // Your code goes in here.
    var records = openZipCodeStudyRecordSet(),
        zipArray = [],
        zipUnique = [];
    while (records.readNextRecord()) {
        var zips = records.getSampleZipCode();
        zipArray.push(zips);
        zipArray.sort();
    }
    for (var x = 0; x < zipArray.length; x++) {
        if (zipArray[x] !== zipArray[x-1]) {
            zipUnique.push(zipArray[x]);
        }
    }
    var output = document.getElementById('outputDiv');
    for (var y = 0; y < zipUnique.length; y++) {
        output.innerHTML += zipUnique[y] + "<br>";
    }
})();

into my html and it works perfectly, but when I put it into an external JavaScript file, I get an error of:

Uncaught TypeError: Cannot read property 'innerHTML' of null

for my:

output.innerHTML += zipUnique[y] + "<br>";

below is the link to the image with the example of the error and highlighting the line that has the error when I put the code into an external js file.

enter image description here

Is it not possible to put self-invoking functions (IIFE) into an external JavaScript file and use it in an html file? Why does my code work perfectly when in an HTML script tag, but not in an external JavaScript file?

A J
  • 3,970
  • 14
  • 38
  • 53
Lee Tou
  • 35
  • 1
  • 1
  • 6
  • 1
    Where exactly did you put it? At the bottom of the page, it should work. You do need that DOM element `outputDiv` to exist first. – Thilo Nov 14 '16 at 04:21
  • my `outputDiv` tag is in my body before the `script` tag. this is how it is put.
    – Lee Tou Nov 14 '16 at 04:24
  • 1
    It seems that your DOM is not ready so make sure by using JQuery that your DOM is ready then you won't get error. – Kumod Singh Nov 14 '16 at 04:27
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Thilo Nov 14 '16 at 04:28
  • Try moving the script tag down more. If you have browser support, try the `defer` attribute (see http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). Otherwise, do it properly and bind to `onReady`. – Thilo Nov 14 '16 at 04:28

1 Answers1

0

May be you are running your JavaScript code before the your HTML document is loaded so move your all code in the window.onload function and after that run your code:

window.onload=function(){
(
    function assignment12_3(){
        // Your code goes in here.
        var records = openZipCodeStudyRecordSet();
        var zipArray = [];
        var zipUnique = [];
    while (records.readNextRecord()) {
        var zips = records.getSampleZipCode();
        zipArray.push(zips);
        zipArray.sort();
    }
    for (var x = 0; x < zipArray.length; x++) {
        if (zipArray[x] !== zipArray[x-1]) {
            zipUnique.push(zipArray[x]);
        }
    }
    var output = document.getElementById('outputDiv');
    for (var y = 0; y < zipUnique.length; y++) {
        output.innerHTML += zipUnique[y] + "<br>";
    }
    }
)();
}

Let me know what you get after using the above solution.

Edit:

When your JavaScript code will be run, It depends on the you where you put the JavaScript code in the HTML document, It does not matter you put the JavaScript code through the External JavaScript File, or put Script tag directly into the HTML document.

Please refer my article here: http://www.javascripthive.info/javascript/adding-javascript-code-to-html/

It needed to use the window.onload function when we are using the self invoking function: NO, there is no relationship between the self invoking function and the window.onload, So if you are using the self invoking function than you don't have any need to use the window.onload function.

window.onload

By using the window.onload function we are simply attaching the event to the window, We are saying the window that when you are ready (means all the components of the HTML document is loaded including the images, script and whole HTML document) than call this function.

So the window will call the function which we assign to the window.onload after the fully HTML document is loaded in the browser.

Your problem is solved because the your code is written inside the window.onload function and this function is called after the whole HTML document is loaded. So your outputDiv is loaded and ready to access using the JavaScript code.

Kalpesh Rajai
  • 2,040
  • 27
  • 39
  • Thank you. Looks like that helped it. Like the others recommended before, I tried moving the script tags down to the bottom of the body section in the html file, but it still didn't do anything different. When I added the `window.onload` function to my javascript file, my code runs perfectly now even without the script tags having to be moved down further. – Lee Tou Nov 14 '16 at 04:37
  • Self-invoking functions by definition self-invoke. Invoke means to run. They are invoked/run at the moment the code is seen. –  Nov 14 '16 at 04:58
  • @torazaburo, Yes you are right, But the `window.onload` is called after the whole document is loaded, If we put the self invoking function inside the `window.onload` than the browser will see that function only when the whole document is loaded and the `window.onload` function is called. So there is no issued with the above code and It solved the problem of the op, you can not down vote this answer. – Kalpesh Rajai Nov 14 '16 at 05:12
  • Thank you @LeeTou, Because you does not have the enough points to up vote. You at least need the 15 points to up vote. – Kalpesh Rajai Nov 14 '16 at 06:17