Reputation: 39
I'm trying to make a web responsive page and and my problem is snapping a div to a fixed navigation bar when I scroll down the page.
https://jsfiddle.net/56jkmvma/1/
Depending on the window size or zoom, the div will either overshoot or undershoot the navigation bar.
My best attempt was to use scrollTop() to prevent further page scrolling once the scrollTop(value) matched the value where the content-div meets the nav bar, but it only worked for 100% zoom and hard coded values.
jQuery
$(window).scroll(function() {
var winHeight = $(window).height();
var navHeight = $('.nav').height();
var stopPoint = winHeight - navHeight;// gives position where scrollTop should stop allowing the div to 'snap' to the nav bar
var scrollPos = $(window).scrollTop();
if (scrollPos == stopPoint) {
$(window).scrollTop(stopPoint);
}
});
I've also tried to use anchors and scrollTo(), but never got one working correctly. Open to any methods, Thanks!
Upvotes: 2
Views: 1181
Reputation: 5953
If I understand well, you are looking for something like this Example
and the code:
$(document).ready(function(){
var heightNav=$('.nav').height();
var posCon=$('.content').offset().top;
var posWin;
$(window).on('scroll',function(){
posWin=$(this).scrollTop()+heightNav;
if(posWin > posCon){
$('.content').css({
position: 'fixed',
top: heightNav,
'margin-top':0
});
}
else {
$('.content').css({
position: 'relative',
'margin-top':'20em',
top:0
});
}
});
});
Upvotes: 2