Reputation: 323
box2 is a fix positioned element, I need it stops at the top and bottom of box1 when scrolling. Any help would be appreciated.
$(window).scroll(function() {
var h1 = $('.box1').height();
var h2 = $('.box2').height();
var h3 = $('.footer').outerHeight(true);
$('.box2').css('bottom', h3);
});
Upvotes: 1
Views: 424
Reputation: 35670
If I understand the question correctly, you want box2
to appear static within the viewport, except it should never go above or below box1
's extent.
Use this code:
$(window).scroll(function() {
var scrollTop= $(window).scrollTop(),
b1= $('.box1'),
b2= $('.box2'),
min= b1.position().top,
max= (b1.position().top + b1.outerHeight()) - b2.outerHeight();
b2.css({
top: Math.min(Math.max(scrollTop,min),max) - scrollTop
});
});
Upvotes: 4
Reputation: 236
Great answer from Rick Hitchcock, made some improvements:
var $b1 = $('.box1'); // 1
var $b2 = $('.box2'); // 1
var min = $b2.position().top; // 2
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var max = ($b1.position().top + $b1.outerHeight()) - $b2.outerHeight();
$b2.css({
top: Math.min(Math.max(scrollTop, min), max)
});
});
min
the original top of $b2
on page load.Upvotes: 1