简体   繁体   中英

show div content as default upon page load Javascript

I want to show one div content (.option-1) when the website is loading.

document.getElementById('target').addEventListener('change', function () {
  let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"
  
  for (let i = 0; i < divs.length; i++) {
    // loop over all divs
    let div = divs[i];
    if (div.classList.contains(this.value)) {
      // the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
      div.classList.remove('initial');
      div.classList.add('vis'); // make the div visible
    } else {
      div.classList.add('initial');
      div.classList.remove('vis'); // otherwise make the divs invisible
    }
  }
  
});

 <div class="header"> <select name="dropdown" id="target"> <option value="option-1">option1</option> <option value="option-2">option2</option> </select> </div> <div class="temps"> <div class="initial option-1">Temp 1</div> <div class="initial option-2">Temp 2</div> </div> <div class="forms"> <div class="initial option-1">Form 1</div> <div class="initial option-2">Form 2</div> </div>

.initial display none;

 .initial { display: none; }

If you want the first option in the dropdown to run the logic on load, add a load event listener with a DispatchEvent that will emulate a change on the dropdown.

window.addEventListener('load', function() {
  let event = new Event('change');
  document.getElementById('target').dispatchEvent(event);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM