Reputation: 1814
I'm using this code to make my nav sticky after #header1
div. It works fine for me but the issue is my console shows an error
Uncaught TypeError: Cannot read property 'top' of undefined
Please provide me some solutions for it. Thanks
$(document).ready(function () {
$(window).bind('scroll', function () {
var navHeight = $(".header1").height();
($(window).scrollTop() > navHeight) ? $('.afterLgnRow').addClass('goToTop') : $('.afterLgnRow').removeClass('goToTop');
});
});
$('.afterLgnRow').affix({
offset: {
top: $('#header1').offset().top
}
});
Upvotes: 0
Views: 259
Reputation: 337610
The problem is because offset()
is returning nothing as you're attempting to work with the #header1
element before the DOM is ready. To fix this move the code inside the document.ready handler.
Also note that bind()
is deprecated, use on()
instead, and you can simplify the addClass()
/removeClass()
logic by using toggleClass()
with a boolean.
$(document).ready(function () {
$(window).on('scroll', function () {
var navHeight = $(".header1").height();
$('.afterLgnRow').toggleClass('goToTop', $(window).scrollTop() > navHeight);
});
$('.afterLgnRow').affix({
offset: {
top: $('#header1').offset().top
}
});
});
I also note that you're accessing both #header1
and .header1
- ensure these selectors are correct.
Upvotes: 3