Uncaught TypeError: Cannot read property 'top' of undefined

edubba picture edubba · Nov 24, 2013 · Viewed 319.2k times · Source

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.

Answer

Guffa picture Guffa · Nov 24, 2013

Check if the jQuery object contains any element before you try to get its offset:

var nav = $('.content-nav');
if (nav.length) {
  var contentNav = nav.offset().top;
  ...continue to set up the menu
}