简体   繁体   中英

How do I get my function to run when a criteria is met?

I've written some code in JS that's basically supposed to work like a CSS media query and start this slideshow when the viewport width threshold has been crossed. I know it works because it runs when I call the function in the console, but I cannot figure out why it won't just run on it's own as intended.

I'm guessing I've either done something wrong with the responsive part or there's a super basic error somewhere that I've yet to learn.

So far I've tried "window.InnerWidth", I've tried "screen.width" "document.body.clientWidth" and "window.matchMedia" (and to be honest, I would love to know more about each because I'm fairly new to JS).

Here's the snippet:

function resetCards() {
  card.forEach(elem => elem.classList.remove("show"));
}
function showCards(index) {
  resetCards();
  card[index].classList.add("show");
}
function cardSlide() {
  var i = 1;

  function loop() {
    setTimeout(function() {
      showCards(i);
      i++;
      if (i < card.length) {
        loop();
      } else if (i == card.length) {
        i = 0;
        loop();
      }
    }, 4000);
  }
  loop();
}

function runShow() {
  var i = window.matchMedia("(max-width: 1024px)");
  if (i.matches) {
    cardSlide();
  } else {
    console.log("Error!");
  }
}
runShow();

Your code only checks once . But the good news is that matchMedia returns an object that as a change event you can hook into that gets triggered whenever the result of the media query changes:

function runShow(e) {
  if (e.matches) {
    cardSlide();
  }
}
window.matchMedia("(max-width: 1024px)").onchange = runShow;

If you want it to run once right away, you need to do that proactively:

function runShow(e) {
  if (e.matches) {
    cardSlide();
  }
}
var match = window.matchMedia("(max-width: 1024px)");
match.onchange = runShow;
runShow(match);

Live Example

That example doesn't do anything when the query goes from matching to non-matching. You might want to do something in an else or similar.

The reason it won't check the width after a certain time is because you are using the setTimeout function, this will only run once. If you want it to check multiple times you should use the setInterval function.

You however want to avoid this as it is not accurate / efficient. you could use eventlisteners instead!

Like one of the answers here stated, you are able to use the onchange event of the window.matchMedia object.

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