Uncaught TypeError: Cannot read property 'top' of undefined
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
}
Getting the error Cannot read property 'top' of undefined
The error means that $(cache).offset()
is returning undefined
, which in jQuery terms generally means that $(cache)
didn't find anything.
From the layout of your script, it seems that you're likely executing this code right away and the element(s) your looking for may not exist yet (since the document is still loading). Try executing it after the document has fully loaded. In jQuery you can accomplish this by wrapping the code in the jQuery function itself, which by default sets it as a handler to the document's ready
event:
$(function () {
var cache = '.faixatrabalho';
console.log( cache );
//store the initial position of the element
var vTop = $(cache).offset().top - parseFloat($cache.css('margin-top').replace(/auto/, 0));
});
Cannot read properties of undefined (reading 'top') happens on every page except homepage
That's probably because the element that matches the #scroll
selector does not exist on those pages that threw the error. When that happens, $('#scroll').offset()
returned undefined
, and you cannot access top
from undefined
.
To fix this, you will probably need to ensure the element exists before attempting to invoke the logic:
const $scroll = $('#scroll');
if ($scroll.length) {
$('html,body').animate({
scrollTop: $scroll.offset().top
}, 'fast');
}
Cannot read property 'top' of undefined Jquery/javascript
The issue was that the code wasn't specific enough. The loop was iterating through all the items in the list, that is all the links that where #tags, and links to other pages. That is the reason i was getting the error of top not defined, that item it was looking for didn't exist. a[href^="#"'
after adding that, loop only iterated the items with # ID tags.
Commented the changes i made
//smooth transition to sctions when links in header are clicked
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('nav.mobile-nav a[href^="#"').each(function () { //added a[href^="#"] so that the loop only iterates over the elements with the ID tag
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
console.log(currentLink.attr("href")); //log
if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
$('nav.mobile-nav a').removeClass("current");
currentLink.addClass("current");
}
else{
currentLink.removeClass("current");
}
});
}
$(document).ready(function () {
$(document).on("scroll", onScroll);
$('nav.mobile-nav a[href^="#"], .arrow-down-wrapper a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('nav.mobile-nav a').each(function () {
$(this).removeClass('current');
});
$(this).addClass('current');
var target = this.hash;
$target = $(target);
console.log(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 100
}, 1000, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
Uncaught TypeError: Cannot read property top of undefined
Since not all of your links have their href value as a valid CSS selectors, you'll have to check if something is selected before accessing the position
. Try this:
$('.header-body a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if(!refElement.length) return; // if the length is 0 (nothing selected) skip the rest of this iteration where the accessing of the position happens
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.header-body a').removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
JavaScript - Cannot read property 'top' of undefined
if ($("#aboutUs").length) {
if ($("#aboutUs").offset().top > 100) {
$("#aboutUs").addClass("visible");
} else {
$("#aboutUs").removeClass("visible");
}
}
Maybe your jquery code is running before view is rendered and Its not able to find element with id "aboutUs". So first check for the element existence and then write your code
Related Topics
How to Append a Div Inside an Svg Element
Change Form Values After Submit Button Pressed
Shrink Div to Text That's Wrapped to Its Max-Width
How to Apply CSS to the Elements Within an Iframe
Understanding Cross-Domain Issue in Iframes
HTML Comments in a JavaScript Block
Conditional Comment for 'Except IE8'
Save a Pre Element as PDF with CSS
Localstorage Access from Local File
How to Run HTML Files Directly from Github, Instead of Just Viewing Their Source
React: Why Child Component Doesn't Update When Prop Changes
Jquery VS Document.Queryselectorall
Create a Simple 10 Second Countdown
Resize a Div on Border Drag and Drop Without Adding Extra Markup
Adding Rows Dynamically with Jquery
Create a String of Variable Length, Filled with a Repeated Character
Img-Src' Was Not Explicitly Set, So 'Default-Src' Is Used as a Fallback