user5854648
user5854648

Reputation: 1121

Why won't navbar fix to the top?

This code works when I take out the check of window width. Once I add in a reference to the window width the code no longer works. I only want the navbar to become fixed on screen sizes smaller than 768px. I'm rusty with jQuery so help is appreciated.

$(document).ready(function() {
  var width = $(window).width();

  $(window).scroll(function() {
    if ($(width) < 768) {
      if ($(this).scrollTop() > 567) {
        $('.navbar').css('position', 'fixed').css('top', '0');
      } else {
        $('.navbar').css('position', 'relative');
      }
    } else {
      $('.navbar').css('position', 'relative');
    }
  })

  $(window).resize(function() {
    if ($(width) < 768) {
      if ($(this).scrollTop() > 567) {
        $('.navbar').css('position', 'fixed').css('top', '0');
      } else {
        $('.navbar').css('position', 'relative');
      }
    } else {
      $('.navbar').css('position', 'relative');
    }
  });
});

Upvotes: 0

Views: 47

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

The main issue here is that you're placing width within a jQuery object when this is not necessary. Just use width directly in the conditions:

if (width < 768)

That being said, your code can be DRY'd up and also improved through the use of CSS classes and media queries. Try this:

jQuery(function($) {
  $(window).on('scroll resize', function() {
    $('.navbar').toggleClass('fixed', $(this).scrollTop() > 567);
  });
});
html,
body {
  height: 2000px;
  padding: 0;
  margin: 0;
}

.navbar {
  padding: 10px;
  background-color: #CCC;
}

@media only screen and (max-width: 768px) {
  .navbar.fixed {
    position: fixed;
    top: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">Navbar</div>

Upvotes: 2

Related Questions