A Quick jQuery Solution For a Fixed Website Menu

Fixed headers are popular across sites with lengthy content


With Beard Profile, we decided to make the website’s header fixed. This should fix issues with long-scrolling article content, and most definitely the Newsfeed content. We initially had a Back to Top button, but a fixed menu seems to be a better option when it comes to keeping visitors navigating on your website.

This is expected to be modified for your own header. It took me all of two minutes to set this up on the site which initially had a static header that stayed at the top.

jQuery:

<script>
$(function(){
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 40) {
            $('.site_panel').addClass('stickyPanel');
        }
        else {
            $('.site_panel').removeClass('stickyPanel');
        }
    });
});
</script>

CSS:

.site_panel {
    position: relative;
    top: 0;
    background: #fff url(images/repeat.png) scroll repeat 0 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.15);
    box-shadow: 0 0 8px -5px #000;
}

.stickyPanel {
    position: fixed;
    width: 1160px;
    max-width: 100%;
    z-index: 999;
    border-top: 0;
    top: 0;
    left: 50%;
    transform: translate(-50%, 0);
}

That’s all the CSS I needed to get the menu fixed. This menu is also at a fixed width, so that’s why you’re seeing the left and transform in the stickyPanel selector. This keeps the menu centered on the screen. Simply remove those two lines and change 1160px to 100% if you’re using a full-width menu.

The number in this line of the JS should also be changed:

if ($(this).scrollTop() >= 40)

It’s a px value as to when your sticky menu kicks in, depending on your website’s layout.