jQuery scroll to function giving "Cannot read property 'top' of undefined" - javascript

I'm having a little trouble with a simple scroll to action I have made, I keep getting the following error:
Uncaught TypeError: Cannot read property 'top' of undefined
JSFiddle example: http://jsfiddle.net/cvLcsgm3/
JS:
// ordering page
$('#order-details').hide();
$('#order-details').on('click touchstart', function () {
$(this).show();
//showTarget(this.hash);
});
// Scroll To # Links
$('a[href*="#"]').click(function(e) {
//if (!$(this).hasClass('menu-button')) {
//e.preventDefault();
showTarget(this.hash);
$('body').removeClass('menu-open');
//}
});
$(window).load(function(e){
showTarget(window.location.hash);
});
function showTarget(target) {
target = target.replace('#', '');
if (target) {
$('html, body').animate({scrollTop: $('.' + target).offset().top}, 700, 'swing', function() {
window.location.hash = '#' + target;
});
}
}
Any ideas why I'm getting that error and how I can resolve it?

Related

How Do I Use Scrollspy when I have links on the page and off the page?

I have an application with a landing page that has many sections, and use Scrollspy for the smooth scrolling effect in the page. At the end of my navigation items I have a call to action button that takes the user to another page. However, because it's in my navigation items, when the page loads, Scrollspy is throwing an error on the link to another page.
Uncaught Error: Syntax error, unrecognized expression: https://example.com/page2
Is there anything I can do to tell scrollspy to ignore that link or is there some other way to get rid of that error? Thanks!
Here is the code I am using to initialize scrollspy:
(function ($) {
'use strict';
// SmoothLink
function initSmoothLink() {
$('.nav-item a').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 0
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
}
// StickyMenu
function initStickyMenu() {
$(window).on('scroll',function() {
var scroll = $(window).scrollTop();
if (scroll >= 50) {
$(".sticky").addClass("stickyadd");
} else {
$(".sticky").removeClass("stickyadd");
}
});
}
// Scrollspy
function initScrollspy() {
$("#navbarCollapse").scrollspy({
offset: 70
});
}
//MFPVideo
function initMFPVideo() {
$('.video_play').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false
});
}
// Back To Top
function initBackToTop() {
$(window).on('scroll',function(){
if ($(this).scrollTop() > 100) {
$('.back_top').fadeIn();
} else {
$('.back_top').fadeOut();
}
});
$('.back_top, .footer_logo_link').on('click',function(){
$("html, body").animate({ scrollTop: 0 }, 1000);
return false;
});
}
function init() {
initSmoothLink();
initStickyMenu();
initScrollspy();
initMFPVideo();
initBackToTop();
}
$(document).on('turbolinks:load', function(){
init();
});
})(jQuery);
You can add in if statement to check if the href has a hash. If it doesn't have one, then it will just proceed as normal.
function initSmoothLink() {
$('.nav-item a').on('click', function(event) {
var $anchor = $(this);
if (this.hash !== "") {
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 0
}, 1500, 'easeInOutExpo');
event.preventDefault();
}
});
}
Scrollspy looks for all a tags in given container, takes href attribute and uses it's value as jQuery selector. Here is the possible solution using JS:
Page 2
Setting href and id is required in your case if you don't want to add additional checks in initSmoothLink() function.

How to fix 'Uncaught ReferenceError: $ is not defined' [duplicate]

This question already has answers here:
Uncaught ReferenceError: $ is not defined?
(40 answers)
Closed 3 years ago.
This is for a navigation header and it works, but I still get an error on line 2. VM4582 header.js:2 Uncaught ReferenceError: $ is not defined
I don't understand why it says $(window) is not defined.
// Sticky Header
$(window).scroll(function() {
if ($(window).scrollTop() > 100) {
$('.main_h').addClass('sticky');
} else {
$('.main_h').removeClass('sticky');
}
});
// Mobile Navigation
$('.mobile-toggle').click(function() {
if ($('.main_h').hasClass('open-nav')) {
$('.main_h').removeClass('open-nav');
} else {
$('.main_h').addClass('open-nav');
}
});
$('.main_h li a').click(function() {
if ($('.main_h').hasClass('open-nav')) {
$('.navigation').removeClass('open-nav');
$('.main_h').removeClass('open-nav');
}
});
// navigation scroll lijepo radi materem
$('nav a').click(function(event) {
var id = $(this).attr("href");
var offset = 70;
var target = $(id).offset().top - offset;
$('html, body').animate({
scrollTop: target
}, 500);
event.preventDefault();
});
If you are using $ then you are dealing with jQuery and this error will occure when you dont add jQuery cdn or jquery reference script file so kindly check the jQuery cdn and paste it in your head section and this will solve your problem.

Cannot read property 'addClass' of undefined with smoothState.js in Wordpress

I'm trying to implement smoothState.js into a custom WordPress theme. I'm flummoxed. I feel like my code is correct according to the smoothState documentation, but it's still producing an error. But I'm still a beginner at JS/JQuery and scripting in general so I'm probably missing something.
Using JQMigrate version 1.4.1 and JQuery 1.12.4 in noConflict mode. WordPress is 4.6.1.
jQuery(document).ready(function($){ // WordPress doesn't release $ so we need this line
$(function() {
var $body = $('html, body'),
content = $('#wrapper').smoothState({
prefetch: true,
pageCacheSize: 4,
debug: true,
// onStart is for when a link is clicked
onStart: {
duration: 2500, // animation duration in ms
render: function (url, $container) {
$container.addClass('is-exiting');
$body.animate({
scrollTop: 0
});
smoothState.restartCSSAnimations();
}
},
onEnd : {
duration: 1500, \
render: function (url, $container, $content) {
$container.removeClass('is-exiting');
$body.css('cursor', 'auto');
$body.find('a').css('cursor', 'auto');
$container.html($content);
// Trigger document.ready and window.load
$(document).ready();
$(window).trigger('load');
}
},
onAfter : function(url, $container, $content) {
}
}).data('smoothState');
});
(function($, undefined) {
var isFired = false;
var oldReady = jQuery.fn.ready;
$(function() {
isFired = true;
$(document).ready();
});
jQuery.fn.ready = function(fn) {
if(fn === undefined) {
$(document).trigger('_is_ready');
return;
}
if(isFired) {
window.setTimeout(fn, 1);
}
$(document).bind('_is_ready', fn);
};
})(jQuery);
});
Clicking any hyperlink inside #wrapper throws the following console error...
Uncaught TypeError: Cannot read property 'addClass' of undefined
w # jquery.smoothState.min.js:9
b # jquery.smoothState.min.js:9
dispatch # jquery.js?ver=1.12.4:3
r.handle # jquery.js?ver=1.12.4:3
I've checked for any potential plugin or theme conflicts and found none. I've even tried explicitly declaring the container like var $container = $("#wrapper"); but still get the same results. Any ideas?
After looking over the smoothState onStart documentation it seems the render function only accepts a single argument like so:
$('#main').smoothState({
onStart: {
// How long this animation takes
duration: 0,
// A function that dictates the animations that take place
render: function ($container) {}
}
});
Your code has two:
render: function (url, $container) {
This would likely cause your render function url argument to be set to $container as it is the first argument passed, and the $container argument to be undefined, as the argument is never passed/set. Thus, when you call:
$container.addClass('is-exiting');
You receive the error:
Cannot read property 'addClass' of undefined
Because $container is not an object.

Scrolling to an element using jQuery

I'm getting a few errors and not sure why.
I just want it to scroll to the parents div ID when it's clicked, it's getting the ID okay as I did a console log, so the issue is the scrolling part.
Error:
Uncaught TypeError: clickedPanel.offset is not a function
JS
$('#accordion .panel-heading .panel-title').click(function() {
$(this).parent().next().slideToggle(iconCallback);
$(".panel-collapse").not($(this).parent().next()).slideUp(iconCallback);
//scroll to clicked pabel
var container = $('#accordion'),
clickedPanel = $(this).parent().attr('id');
container.animate({
scrollTop: clickedPanel.offset().top - container.offset().top + container.scrollTop()
})
function iconCallback() {
var iconClass = $(this).is(':visible') ? 'fa-minus' : 'fa-plus';
$(this).prev().find('i').removeClass('fa-plus fa-minus').addClass(iconClass);
}
});
In your example clickedPanel is a string which does not have the offset() method. Instead set that variable to be the jQuery object returned from parent():
clickedPanel = $(this).parent();

Console Error: Uncaught TypeError: Cannot read property 'top' of undefined

I'm trying to get a div class to scroll to the top when .recipeImgs li is clicked. I tried the code below but i am getting the error message
Uncaught TypeError: Cannot read property 'top' of undefined". Not sure how to fix the issue
Thanks
$('.recipeImgs li').on('click',function (e) {
e.preventDefault();
console.log("clicked");
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-50
}, 900, 'swing', function () {
window.location.hash = target;
});
});
The issue, as someone pointed out in one of the comments, is that $target has no element, which means that the .offset() method returns undefined. Obviously there is no property top on undefined, hence the error.
You might reconsider writing your function something like this:
$(document).on('click', '.recipeImgs li', function(evt){
evt.preventDefault();
var $target = $(this);
if(!$target.length) return;
$('html, body')
.stop()
.animate({
'scrollTop': $target.offset().top - 50
}, 900, 'swing', function(){
window.location.hash = '[target]';
})
});
This fixes several things. First of all, it delegates the listener to the document, so if your li is dynamically appended, you'll still be able to grab the event (as it bubbles up the DOM). There's also a check for $target.length. This just ensures that you don't try to retrieve the offset of an empty collection, resulting in an error and breaking your code.

Categories

Resources