Question3r
Question3r

Reputation: 3782

Create a div area for toast notifications by using Javascript

for my toast notifications I create a div container called "toastArea". So when I write in my HTML file

<div class="toastArea"></div>

everything is fine. But I want to create it dynamically by using JS. So in my toast controller I write

class ToastController { // class for toast notifications
  constructor() {
    this.CreateToastArea(); // create a div for every toasts
  }

    CreateToastArea() {
      var area = document.createElement("div"); // create div
      area.classList.add("toastArea"); // add a class to the div
      document.body.appendChild(area); // append div to the body
    }
}

but when the constructor calls the function it says

Cannot read property 'appendChild' of null

but the variable "area" is not null. The div got created correctly.

I don't get what's wrong there..

Upvotes: 0

Views: 914

Answers (1)

Don Rhummy
Don Rhummy

Reputation: 25830

Your script is loaded in the header. You need to tie the instantiation of your ToastController to the loading/parsing of the body.

For example, in jQuery:

jQuery( document ).ready( function() { window.myToastController = new ToastController(); } );

Upvotes: 1

Related Questions