Reputation: 398
I got an error like "Uncaught TypeError: Cannot read property 'top' of undefined "... I don't know the way to fix!!.. can anybody tell me the answer!!!..var divPos = $(theID).offset().top;
var aChildren = $("nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+85; // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top;// get the offset of the div from the top of page.... error occured here!!!
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("active");
} else {
$("a[href='" + theID + "']").removeClass("active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("active")) {
var navActiveCurrent = $(".active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("active");
$("nav li:last-child a").addClass("active");
}
}
});
Upvotes: 1
Views: 16715
Reputation: 398
I just changed the
var divPos = $(theID).offset().top;
to
var divPosid = $(theID);
if (!divPosid.length) {
return;
}
var divPos = divPosid.offset().top; // get the offset of the div from the top of page
Upvotes: 3
Reputation: 11
Put
console.log(theID);
var divPos = $(theID).offset().top;
And you'll get your answer.
Upvotes: 0