aaronfty
aaronfty

Reputation: 11

How to disable a jQuery function after screen resize

I'm trying to disable this navigation code after the screen is less than 1000px

$(document).ready(function(){
   var scroll_start = 0;
   var startchange = $('body');
   var offset = startchange.offset();
    if (startchange.length){
   $(document).scroll(function() {
      scroll_start = $(this).scrollTop() > 50;
      if(scroll_start > offset.top) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
          $("#nav").css('box-shadow', '4px 0px 10px rgba(0,0,0,0.5)');
       } else {
          $('#nav').css('background-color', 'rgba(35,46,63,0)');
          $("#nav").css('box-shadow', '0px 0px 0px rgba(0,0,0,0)');
       }
   });
    }
});

Any help would be appreciated!

Upvotes: 1

Views: 356

Answers (3)

szegheo
szegheo

Reputation: 4425

Based on your code with slight modification I would do this as follows:

$(document).ready(function(){
  var scroll_start = 0;
  var startchange = $('body');
  var offset = startchange.offset();
  var doScrollStuff;

  $(window).resize(function(){
    doScrollStuff = $(window).width() >= 1000;
  }).resize();

  if (startchange.length){
    $(document).scroll(function() {
      if (doScrollStuff) {
        scroll_start = $(this).scrollTop() > 50;

        if(scroll_start > offset.top) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
          $("#nav").css('box-shadow', '4px 0px 10px rgba(0,0,0,0.5)');
        } else {
           $('#nav').css('background-color', 'rgba(35,46,63,0)');
           $("#nav").css('box-shadow', '0px 0px 0px rgba(0,0,0,0)');
        }
      }
    });
  }
});

Upvotes: 1

Ben K
Ben K

Reputation: 3

You can try this:

var windowWidth = $(window);
windowWidth.on('resize', function(){
    if(window.innerWidth < 1000){
        //do something
    }
})

In the //do something section, you can write your disable function in there. This code above will execute the inner function whenever the screen resizes and is less than 1000px.

Upvotes: 0

Travis J
Travis J

Reputation: 82267

Use onjQuery API to bind the event and use a specific name to easily unbind it later.

$(document).on("scroll.Nav", function () {

And then later, if some condition is met either in the callback of that function(){ code segment, or in another code segment, simply use

$(document).off("scroll.Nav");

Upvotes: 0

Related Questions