I apologize if this question has already been answered. I've tried searching for solutions but could not find any that suited my code. I'm still new to jQuery.
I have two different types of sticky menus for two different pages. Here's the code for both.
$(document).ready(function () {
var contentNav = $('.content-nav').offset().top;
var stickyNav = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > contentNav) {
$('.content-nav').addClass('content-nav-sticky');
} else {;
$('.content-nav').removeClass('content-nav-sticky')
}
};
stickyNav();
$(window).scroll(function () {
stickyNav();
});
});
$(document).ready(function () {
var stickyNavTop = $('.nav-map').offset().top;
// var contentNav = $('.content-nav').offset().top;
var stickyNav = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav-map').addClass('sticky');
// $('.content-nav').addClass('sticky');
} else {
$('.nav-map').removeClass('sticky');
// $('.content-nav').removeClass('sticky')
}
};
stickyNav();
$(window).scroll(function () {
stickyNav();
});
});
My problem is that the code for the sticky side menu on the bottom doesn't work because the second line of code var contentNav = $('.content-nav').offset().top;
fires a error that reads "Uncaught TypeError: Cannot read property 'top' of undefined". In fact, no other jQuery code below that second line works at all unless they are placed above it.
After some researching, I think the problem is that $('.content-nav').offset().top
can't find the specified selector because it's on a different page. If so, I can't find a solution.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…