3

In the controller I have

  init(){
    this._super(...arguments);
    document.body.classList.add("darkMode");
    document.getElementById('mode').src = 'assets/images/logo-white'
  }

and in the handlebars:

<img id="mode" src="assets/images/logo-black.png" alt="white-theme" width="188px" height="56px">

While trying to apply a dark-theme to my project, I successfully added the class to it, but when I tried changing the logo img src by finding its id, it crashes (as in nothing is showing anymore), this is probably because the init() does everything before loading the actual image and cannot take the id from img. I have no solution to this yet, so any idea would be awesome.

I am doing it this way just to test, later I will add an if clause to test whether the user wants to have dark-mode on or not

1 Answers1

1

You are correct. The init hook of any component instance will be executed before the proper construction of the component's DOM (template) and hence we cannot access the DOM at this point. You can move all your DOM related logic to another lifecycle hook of the component called didInsertElement which will be called only after the construction of DOM.

This twiddle should help you!

However, making the templates declarative instead of manually updating the DOM is recommended to avoid unintentional bugs. Here, in this case, the template can be declaratively written as

<img src={{if this.isDarkTheme "logo-white.png" "logo-white"}} width="188px" height="56px">

so that changing the state isDarkTheme will be just enough to track all the related DOM/UI pieces.

Gokul Kathirvel
  • 1,590
  • 1
  • 10
  • 20