My goal is to have 3 div
elements scroll over each other, with their positions fixed when they reach the top. Everything works fine until the window is resized, requiring a page refresh. Is there a way to achieve this without refreshing the page?
Using the resize function didn't work for me, and I'm unsure if that's the correct approach.
Here is my code on JSFiddle:
var $cache = $('#two');
var $cache2=$('#three');
var vTop = $cache.offset().top - parseFloat($cache.css('margin-top').replace(/auto/, 0));
var vTop2 = $cache2.offset().top - parseFloat($cache2.css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
var vTop = $cache.offset().top - parseFloat($cache.css('margin-top').replace(/auto/, 0));
var vTop2 = $cache2.offset().top - parseFloat($cache2.css('margin-top').replace(/auto/, 0));
});
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= vTop) {
$cache.addClass('stuck');
$('#one').addClass('stuck');
$('#two h2').addClass('stuck');
} else if(y>=vTop2)
{
$('#two h2').removeClass('stuck');
}
else {
$cache.removeClass('stuck');
$('#one').removeClass('stuck');
$('#two h2').removeClass('stuck');
}
});