简体   繁体   中英

Having JavaScript if statement run periodically and not once without using setInterval

I'm currently running an if statement looped by setInterval 100ms to add and remove classes when the browser is scrolled more than 450px. Obviously, not looping it makes it only run once which is not what I want. I've heard setInterval may lag the browser though, so is there a way to optimize this code better?

setInterval(function() {
  if(window.scrollY > 450) {
    document.querySelector('.whatever').classList.remove("whatever2);
  } else {
    document.querySelector('.whatever').classList.add("whatever3");
  }
}, 100);

The code works in this manner, but obviously I want it as optimized as possible. I used to use jQuery, and I was able to replicate this with document.ready as so:

$(document).ready(function(){
    $(window).scroll(checkScroll);
    function checkScroll() {
        if($(window).scrollTop()>=450) {
            $('.whatever').addClass('whatever2');
        }else{
            $('.whatever').removeClass('whatever3');
        }
    }
});

I struggle converting it to JavaScript in a better manner though.

Try:

 document.addEventListener('DOMContentLoaded', function() { window.addEventListener('scroll', checkScroll) function checkScroll() { if (window.scrollY >= 450) { document.querySelector('.whatever').classList.add('whatever2'); } else { document.querySelector('.whatever').classList.remove('whatever3'); } } })
 html, body{ height:200%; } .whatever{ position:fixed; top:0; left:0; } .whatever2{ background-color:red; } .whatever3{ background-color:blue; }
 <div class="whatever whatever3"> Hello World! </div>

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