make "is-selected" class a part of startup

46 Views Asked by At

I am trying to make a toggle button be ON by default when the webpage loads. I am using Microsoft's Fabric UI.

When I try to add is-selected to <label for="demo-toggle-3" class="ms-Toggle-field" tabindex="0"> it will remove the is-selected when the page starts. However, I can add it later to the tag by using the inspection tools in Chrome.

Here is the code I used:

HTML

<div class="ms-Toggle">
  <span class="ms-Toggle-description">Let apps use my location</span> 
  <input type="checkbox" id="demo-toggle-3" class="ms-Toggle-input" />
  <label for="demo-toggle-3" class="ms-Toggle-field is-selected" tabindex="0">
    <span class="ms-Label ms-Label--off">Off</span> 
    <span class="ms-Label ms-Label--on">On</span> 
  </label>
</div>

JavaScript

<script type="text/javascript">
  var ToggleElements = document.querySelectorAll(".ms-Toggle");
  for (var i = 0; i < ToggleElements.length; i++) {
    new fabric['Toggle'](ToggleElements[i]);
  }
</script>

However when the page loads, it comes out like this:

<div class="ms-Toggle">
  <span class="ms-Toggle-description">Let apps use my location</span> 
  <input type="checkbox" id="demo-toggle-3" class="ms-Toggle-input" />
  <label for="demo-toggle-3" class="ms-Toggle-field" tabindex="0">
    <span class="ms-Label ms-Label--off">Off</span> 
    <span class="ms-Label ms-Label--on">On</span> 
  </label>
</div>
1

There are 1 best solutions below

0
AudioBubble On

Thanks to @HereticMonkey I was able to solve the issue by adding the is-selected class to the toggle element after its been created. Since I have multiple toggles, I used a forloop like so:

for (var i = 0; i < ToggleElements.length; i++) {ToggleElements[i].querySelector('.ms-Toggle-field').classList.add('is-selected')}