Search code examples
javascripthtmlonsen-ui

Button not sharing action between tabs


I am using Onsen UI framework. I have an HTML app which contains 3 tabs (tab1, tab2 and tab3). All the code is under the same HTML file. In tab1, I have a button that when is checked the h2 changes colour. This change is made just on tab1 but I want the change in all of the three tabs.

Basically, this is the idea:

HTML

  <template id="tab1.html">
      <ons-page id="tab1">
        <!-- This is the button --> <ons-switch id="nightmode"></ons-switch>
      </ons-page id="tab1">
      <h2 class="title">Home</h2>
  </template id="tab1.html">

  <template id="tab2.html">
      <ons-page id="tab2">
          <h2 class="title">Home</h2><!-- It shall change colour, but it does not -->
      </ons-page id="tab2">
  </template id="tab2.html">

  <template id="tab3.html">
      <ons-page id="tab3">
       <h2 class="title">Home</h2><!-- It shall change colour, but it does not -->
      </ons-page id="tab3">
 </template id="tab3.html">

JS

<script>
document.getElementById("nightmode").addEventListener("change", function() {
  if (document.getElementById("nightmode").checked == true) {
    document.getElementsByClassName("title")[0].setAttribute("style", "color: white;");

  } else {
    document.getElementsByClassName("title")[0].setAttribute("style", "color: black;");
  }
});
</script>

Solution

  • document.getElementsByClassName("title")[0].setAttribute("style", "color: black;");
    

    This code changes first element only, because of [0]. You can change all elements with this code;

    document.getElementById("nightmode").addEventListener("change", function() {
      var elms = document.getElementsByClassName("title");
    
      var textcolor = "white";
      if(document.getElementById("nightmode").checked)
         textcolor = "black";
    
      for(var i in elms){
         var elm = elms[i];
         elm.style.color = textcolor;
      }
    });
    

    Also, I suggest using jQuery. With jQuery, it can be easier;

    $("#nightmode").change(function() {
        if(this.checked)
            $("h2.title").css("color", "white");
        else
            $("h2.title").css("color", "black");
    }