简体   繁体   中英

JavaScript execute page resize and reload event simultaneously

I am trying to execute a window resize and page reload event simultaneously. When the screen size is less than 768 px, I am adding an attribute to an element. I also need that attribute added when the page is reload and a specific size as well, not just when its resized. The code I have below works, except when my screen size hs < 769 px, it takes a few seconds for the attribute to be added which affects how it looks. Any tips on how I can fix this?

window.onload = function(event) {

var element = document.querySelector('.filter-select');

if (window.innerWidth < 768)  {
  element.classList.add('testing');
  element.removeAttribute("size", "4")
  element.removeAttribute("multiple", "yes")    
} else {
       element.classList.remove('testing');
    }    
}


document.addEventListener("DOMContentLoaded", function(event) {
  var element = document.querySelector('.filter-select');

  function resize() {
    if (window.innerWidth < 768) {
      element.classList.add('testing');
      element.removeAttribute("size", "4")
      element.removeAttribute("multiple", "yes")
    } else {
      element.classList.remove('testing');
    }
  }
  window.onresize = resize;
});

My only guess is that you doubled up the same process under different events and these events happen at different times thus the NOTICABLE lag.. if this doesn't solve.. this is an amazing question I already upvoted..

function resize() {
  var element = document.querySelector('.filter-select')
  if (window.innerWidth < 768) {
    element.classList.add('testing')
    element.removeAttribute("size", "4")
    element.removeAttribute("multiple", "yes")
  }
  else {
    element.classList.remove('testing');
  }
}
window.onload=resize

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