Skip to content
This repository has been archived by the owner on Nov 24, 2020. It is now read-only.

Commit

Permalink
navigation.js: avoid infinite loop when finding ancestor to scroll to
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronO committed Aug 3, 2017
1 parent eaebe53 commit fd742a1
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/js/theme/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ function pageHasElement(id) {
return !!$el.length;
}

/*
Utility functions
*/

// Checks if a jQuery element is empty
function isEmpty(element) {
return element.length === 0;
}

// Any returns true if the predicate is true on any of the elements in the list
function any(arr, predicate) {
return arr.length > 0 && arr.filter(predicate).length > 0;

}

/*
Return the top position of an element
*/
Expand All @@ -69,9 +84,24 @@ function getElementTopPosition(id) {
$parent = $el.offsetParent(),
dest = 0;

// Exit early if we can't find any of those elements
if (any([$scroller, $container, $el, $parent], isEmpty)) {
return 0;
}

dest = $el.position().top;

while (!$parent.is($container)) {
// Note: this could be a while loop, but to avoid any chances of infinite loops
// we'll limit the max iterations to 10
var MAX_ITERATIONS = 10;
for (var i = 0; i < MAX_ITERATIONS; i++) {
// Stop when we find the element's ancestor just below $container
// or if we hit the top of the dom (parent's parent is itself)
if ($parent.is($container) || $parent.is($parent.offsetParent())) {
break;
}

// Go up the DOM tree, to the next parent
$el = $parent;
dest += $el.position().top;
$parent = $el.offsetParent();
Expand Down

1 comment on commit fd742a1

@maxkoryukov
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, this commit fixes GitbookIO/gitbook#1525

Please sign in to comment.