简体   繁体   中英

Only call function after after a specific value on screen resize

I'm trying to call a function on screen resize but only if the screen goes over or under a specific value rather than every time the screen is resized.

In this example, I only want to call a function when the isMobile value has changed.

window.addEventListener('resize', () => {
  if (window.innerWidth < mobileSize) {
    isMobile = true;
  } else {
    isMobile = false;
  }
  // call function only isMobile changes from true to false or vice-versa
});

Just store a reference to the last isMobile value, and check if the value changed inside the function:

window.addEventListener('resize', () => {
  const lastIsMobile = isMobile;
  isMobile = window.innerWidth < mobileSize;
  if (lastIsMobile !== isMobile) woohoo()
});

Note that if isMobile is really an Object or an Array, those are pass by reference in JavaScript, which means that mutating the value of isMobile will mutate the value of lastIsMobile . Booleans are pass by value in JavaScript, though, so lastIsMobile won't be mutated in this way.

Try this:

window.addEventListener('resize', () => {
  const isMobilePrevious = isMobile;
  isMobile = window.innerWidth < mobileSize;

  if (isMobilePrevious === isMobile) return;

  // call your function
});

You can store the last value and check for a change:

window.addEventListener('resize', () => {
  const wasMobile = isMobile;
  if (window.innerWidth < mobileSize) {
    isMobile = true;
  } else {
    isMobile = false;
  }
  // call function only isMobile changes from true to false or vice-versa
  if (wasMobile != isMobile) {
    someFunction();
  }
});

But for responsive design I strongly recommend taking a look at CSS media rules .

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