James Ives
James Ives

Reputation: 3365

Mobile vs Desktop Scroll/Resize Issues

I have a navbar on a page which I want to have stick to the top once it reaches a certain point from the top on desktop devices. On mobile devices (less than 780) I want it to always stick no matter how far on the page has scrolled down.

Right now I'm running into an issue where both of the window scroll/resize events keep toggling the style on and off which is causing all sorts of mayhem. What would be a good way to repurpose this code so it behaves properly and acts seamlessly when the browser is resized?

$(document).ready(function() {
  $(window).scroll(function() {
    var $box = $("#box");

    if ($(window).scrollTop() > 30) {
      $box.addClass("fixed");
    }

    if ($(window).scrollTop() < 30) {
      $box.removeClass("fixed");
    }

    if ($(window).width() > 780) {
      $box.removeClass("fixed");
    }

    if ($(window).width() < 780) {
      $box.addClass("fixed");
    }
  });

});
#box {
  width: 100%;
  background-color: red;
}

.fixed {
  position: fixed;
  top: 0;
}
<div id="box">
  This is the nav
</div>

<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>
<p>
  Content
</p>

Upvotes: 0

Views: 542

Answers (1)

Bradley4
Bradley4

Reputation: 500

Check for the window width first, then only if its a desktop, check the scrollTop.

Based on OPs comment, this now runs on resize and on scroll

$(document).ready(function() {

    function headerFunction(){
        var $box = $("#box");

        if ($(window).width() < 780) {
            $box.addClass("fixed");
        } else {  // window is larger than 780
            if ($(window).scrollTop() > 30) {
                $box.addClass("fixed");
            } else { 
                $box.removeClass("fixed");
            }
        }
    }

    $(window).scroll(function() {
        headerFunction();
    });
    $(window).resize(function(){
        headerFunction();
    });
});

Upvotes: 1

Related Questions