Right now, I\'m able to stick the div
to the top after it scrolls down 320px
but I wanted to know if there is another way of achieving this. Below
Try using the offset().top
of the #navwrap
element. That way the element will be fixed from it's starting position in the document, regardless of where that is. For example:
function fixDiv() {
var $div = $("#navwrap");
if ($(window).scrollTop() > $div.data("top")) {
$div.css({'position': 'fixed', 'top': '0', 'width': '100%'});
}
else {
$div.css({'position': 'static', 'top': 'auto', 'width': '100%'});
}
}
$("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
$(window).scroll(fixDiv);
Example fiddle