Sticky Bar

by someprimetime

HTML

<div data-stuck-position="" id="wat"></div>

CSS

html {
    height: 5000px;
}

#wat {
    margin-top: 100px;
    width: 100%;
    height: 30px;
    background:#eee;
}

#wat.stuck {
    position: fixed;
    margin-top: 0;
    top: 0;
    left: 0;
}

JavaScript

$(function() {
    $(document).on('scroll', function() {
        var scrolled = $(document).scrollTop();
        var $targetDiv = $('#wat');
        var divOffset = $targetDiv.offset().top;
        
        if (scrolled > divOffset && !$targetDiv.hasClass('stuck') && !$targetDiv.attr('data-stuck-position').length) {
            // Grab height of container
             $targetDiv.addClass('stuck').attr('data-stuck-position', scrolled);
                         
            console.log('attach now');
        } else if ($targetDiv.attr('data-stuck-position') && $targetDiv.hasClass('stuck')) {
            if (scrolled < $targetDiv.attr('data-stuck-position')) {
                $targetDiv.removeClass('stuck').attr('data-stuck-position', '');
            }
        }
    });
});