Why does smooth scrolling.js throw "$ target.offset (...) undefined error"?

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() { // commented line below because it adds a hash to the url and a history item // location.hash = target; }); }); } } }); // use the first element that is "scrollable" function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; } }); 
+4
source share
1 answer

This happens when the hash target does not exist. In HTML5, a valid hash target can only be written with an identifier.

So this will not work:

 <a name="#hash">Hash</a> 

But it will be:

 <a id="#hash">Hash</a> 

Since the use of name = "" is not valid HTML5, #hash does not exist on the page, so when you try to link to it like this:

var $ target = $ (this.hash) It returns undefined. Even links with valid hash targets will not smooth out scrolling if they are included after invalid because of this.

+5
source

Source: https://habr.com/ru/post/1493186/


All Articles