I have some javascript that strokes scrolls to any # anchor-id pressed (adaptation of this ). On some pages, it throws an error $target.offset(...) is undefined and stops working, and I donβt understand why.
I did some testing and, as far as I know, correlates with page length. Keeping all variables the same, changing only the amount of content, an error occurred (on the same page).
It is strange that I could not reproduce this effect on jsfiddle , it works fine there, for each length. Does anyone know how to fix this error? What could be the reason for this?
This is the javascript that I use (I link to it at the bottom of each page, right before the </body> and immediately after loading jquery 1.10.2):
$(document).ready(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace(/\/$/,''); } var locationPath = filterPath(location.pathname); var scrollElem = scrollableElement('html', 'body'); $('a[href*=#]').each(function() { var thisPath = filterPath(this.pathname) || locationPath; if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) { var $target = $(this.hash), target = this.hash; if (target) { var targetOffset = $target.offset().top; $(this).click(function(event) { event.preventDefault(); $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
user1694077
source share