0

I have a navbar Bootstrap 4 with a header above it. I want the header to disappear on scroll, but the navbar to sticky to the top.

I have enqueued Jquery in my functions.php.

Here is my CSS, in style.css:

.navbar {position:sticky;}

Here is my script, in header.php:

<script>
var $sticknav = $('.navbar');
$(document).scroll(function() {
    $sticknav.css({position: $(this).scrollTop()>0 ? "sticky":"fixed"});
});</script>

To my understanding, this targets .navbar, and changes the value of 'position' in the element's CSS from 'sticky' to 'fixed' once the user scrolls to the top.

However the element doesn't stick, the CSS doesn't change. What am I doing wrong?

Chris L
  • 109
  • 8
  • Normally `position:sticky` is used instead of JS/jQuery. If you're using JS you would just toggle position `static` and `fixed`. See my [answer on using `sticky` or JS](https://stackoverflow.com/questions/42237406/animate-shrink-navbar-on-scroll-using-bootstrap-4/42250478#42250478). – Carol Skelly Jun 12 '18 at 18:52
  • The navbar has content sticky at the moment, and it sticks when it hits the top of the page. It's just that once I scroll below a certain point, it moves off the top of the page. Edit: ignore this, I was barking up completely the wrong tree, and had accidentally done something which affected how sticky worked. – Chris L Jun 12 '18 at 19:49

1 Answers1

1

I believe you need the swap the css rules.

<script>
var $sticknav = $('.navbar');
$(document).scroll(function() {
    $sticknav.css({position: $(this).scrollTop()>0 ? "fixed":"sticky"});
});</script>

https://codepen.io/anon/pen/QxvJym

igimkd
  • 21
  • 3
  • That still didn't work, but you made me realise what my problem was... And I'm embarrassed. There was no .wrapper or equivalent. I put one in with height:auto and now it works. Thank you :) – Chris L Jun 12 '18 at 19:53