Edozié Izegbu
Edozié Izegbu

Reputation: 67

Window.onload scope issues

So I have been trying to create a function that can collect push all the data in this.courses into a table body with my FetchAll property, but for some reason I keep on getting this error in my FetchAll function in the window.onload:

cannot set innerHTML of undefined

However, when I don't use window.onload and place app.FetchAll() outside of the app scope, running the script at the bottom of the body, I have full access to this.el.

What's going on here?

var app = new function () {
  // code

  //we want to get each course by its id
  this.el = document.getElementById('courses');


  //this is all of our data in an array.
  this.courses=['Biology', 'Chemistry','History','English','Spanish','Geography'];

  //now we want to make the count function

  this.Count = function (data) {
    //the data is the input for waht we wanto count
    var el = document.getElementById('courses');
    var name = 'courses';

    if (data) {
      if (data > 1) {
        // sets the name var to courses
        name = 'courses';
      }
      el.innerHTML = data + '' + name;
    } else {
      el.innerHTML = 'No' + name;
    }
  }

  this.FetchAll = function () {
    var data = ''; // this is what we are going to put the html into
    if (this.courses.length > 0)   {
        for (var i = 0; i < this.courses.length; i++) {
          data += '<tr>';
          data += '<td>' + this.courses[i] + '</td>';
          data += '</tr>';
        }
    }
    this.Count(this.courses.length);
    return this.el.innerHTML = data;

  };

  this.Add = function (data) {

    alert("add something")
  }

}

window.onload = function () {
  app.FetchAll();

}

Upvotes: 2

Views: 176

Answers (1)

Pointy
Pointy

Reputation: 413757

It's not a scope issue, it's just a matter of when things happen as the browser interprets the HTML document. Your initialization code that creates the app object runs before the browser has built the DOM. Because of that, the .getElementById() call is returning null.

It works when you move the code to the end of the <body> because when the code runs in that case the DOM is (mostly) constructed.

The placement of the call to FetchAll() can be in the "load" handler or not if your code is at the bottom. If you put all the code (including the construction of the app object) into the "load" handler, that would also work.

Upvotes: 3

Related Questions