Skip to content

Commit

Permalink
fix: check whole tree for matching anchor, not just event target
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaskuske committed Nov 11, 2018
1 parent 82f2b5d commit 46d9967
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
23 changes: 18 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,39 @@

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
element.hostname === localHostname && element.pathname === localPathname
);
}

/**
* 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) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": [
Expand Down

0 comments on commit 46d9967

Please sign in to comment.