From 46d99677fcc087c8d16f661b6e6a275b6d697abb Mon Sep 17 00:00:00 2001 From: Jonas Kuske <30421456+jonaskuske@users.noreply.github.com> Date: Sun, 11 Nov 2018 10:54:41 +0100 Subject: [PATCH] fix: check whole tree for matching anchor, not just event target --- index.js | 23 ++++++++++++++++++----- package.json | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 490db50..3fed828 100755 --- a/index.js +++ b/index.js @@ -27,7 +27,7 @@ return ( // Is an anchor - element.tagName.toLowerCase() === 'a' && + element.tagName && element.tagName.toLowerCase() === 'a' && // Targets an element element.href.indexOf('#') > 0 && // Target is on current page @@ -35,18 +35,31 @@ ); } + /** + * Walks up the DOM starting from a given element until an element satisfies the validate function + * @param {HTMLElement} element The element from where to start validating + * @param {Function} validate The validation function + * @returns {HTMLElement|boolean} + */ + function findInParents(element, validate) { + if (validate(element)) return element; + if (element.parentNode) return findInParents(element.parentNode, validate); + return false; + } + /** * Check if the clicked target is an anchor pointing to a local element, if so prevent the default behavior and handle the scrolling using the native JavaScript scroll APIs so smoothscroll-Polyfills apply * @param {event} evt */ function handleClick(evt) { - var element = getEventTarget(evt); - if (!isAnchorToLocalElement(element)) return; + var clickTarget = getEventTarget(evt); + var anchor = findInParents(clickTarget, isAnchorToLocalElement); + if (!anchor) return; // If href ends with '#', no id: just scroll to the top - var isScrollTop = element.href.match(/#$/); + var isScrollTop = anchor.href.match(/#$/); // Try to retrieve the targeted element - var targetId = !isScrollTop && element.hash.slice(1); + var targetId = !isScrollTop && anchor.hash.slice(1); var target = !isScrollTop && document.getElementById(targetId); if (isScrollTop || target) { diff --git a/package.json b/package.json index 0f05f52..2bacdf3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "smoothscroll-anchor-polyfill", - "version": "0.9.1", + "version": "0.9.4", "description": "Apply smooth scroll to anchor links to replicate CSS scroll-behavior", "main": "dist/index.js", "browserslist": [