how to execute a function that listens for scrollTop AND matchmedia (mql)

71 views Asked by At

I'd like to execute a listener function (that adds class, "cursor-white") that occurs ONLY IF the 2 following conditions are met.

  1. $(window).scrollTop is 0 (at the top of window)
  2. and the window is <= 900px.

Im struggling with getting the logic right. I've placed the mql inside the interval scroll function. It executes (and the class is added) when the 2 criteria are met which is good, HOWEVER it also executes when I change from greater that 900px to less than 900px wide even if the scroll position is not at the top of the window.

This is obviously not the desired result. How to ensure the class is added ONLY IF those two criteria are met. Any help is greatly appreciated :)

  var didScroll;

  $(window).scroll(function(event) {
    didScroll = true;
});

setInterval(function() {
  if (didScroll) {
  atTop();
  didScroll = false;
  }
}, 250);

function atTop(){
  if ($(window).scrollTop() <= 0){  

    var x = window.matchMedia("(max-width: 900px)")
    myFunction(x) // Call listener function at run time
    x.addListener(myFunction) // Attach listener function on state changes

    function myFunction(e) {
      if (e.matches) {
        if($('.logo').hasClass('invert')){
          $(".header-fixed").addClass("cursor-white");
        }        
    } else{
        $(".header-fixed").removeClass("cursor-white")
      }
    } 
  }
  else {
   $(".header-fixed").removeClass("cursor-white");
  }
}

1

There are 1 answers

0
Nish On

After some tinkering with the logic, I've worked out how to combine the conditions into one listener and simplify the logic. Changed the approach slightly to incorporate the window scrollTop listener inside the mql - makes much more sense that way. Hope someone might find this helpful.

    var x = window.matchMedia("(max-width: 900px)")
    myFunction(x) // Call listener function at run time
    x.addListener(myFunction) // Attach listener function on state changes

      function myFunction(e) {
        if (e.matches && $(window).scrollTop() <= 0) {
          //add class or execute any function//
      } else{
        
        }
      }     
    });