Chris L
Chris L

Reputation: 109

Bootstrap navbar with content above does not stick

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?

Upvotes: 0

Views: 113

Answers (1)

igimkd
igimkd

Reputation: 21

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

Upvotes: 1

Related Questions