0

I'm trying to wrap this code:

if($(window).width() > 980) {
   $(window).on("scroll", function() {
      if($(window).scrollTop() > 20) {
        //add black background
        $(".x-navbar").addClass("active");
        $(".x-navbar .desktop .x-nav li  a").addClass("small-bar");
      } 
      else {
        //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
      }
   });
}

in a function, so that I can disable it under 980px width.

The thing I'm trying to achive is something like this:

create a function as here under:

navBar = function () {
     // the whole code goes here.
}

and then "disable" it in the mobile under 980px width like this:

if($(window).width() < 980) {
    // DON'T run the funcion called "navBar". 
}

The problem I'm having is that if the window gets resized to a width under 980px the code above will not listen to the resize and it will run anyway.

rebatoma
  • 734
  • 1
  • 17
  • 32
Paolo
  • 704
  • 9
  • 24

3 Answers3

1

as I mentioned in comment

$(window).on("scroll resize", function() {
     if($(window).width() > 980) {
      if($(window).scrollTop() > 20) {
        //add black background
        $(".x-navbar").addClass("active");
        $(".x-navbar .desktop .x-nav li  a").addClass("small-bar");
      } 
      else {
        //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
      }
     }else{
         // if window width < 980
         //remove background
        $(".x-navbar").removeClass("active");
        $(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
     }
   });
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

You can register a function that will be called when window.resize method is triggered.

$(window).resize(function () {
    //Here you can check the width
});

Hope this helps.

Ele
  • 33,468
  • 7
  • 37
  • 75
0

This is because once you instantiate a listener, it will not be removed until you explicitly remove it. Check out jQuery's off function to remove a listener. You can then switch between off() and on() depending on the window size.