Skip to content

Commit

Permalink
Handle clicks of A tags with child elements
Browse files Browse the repository at this point in the history
  • Loading branch information
dcsaszar committed Apr 1, 2020
1 parent 6b9acec commit bf6ac05
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@
"test": "karma start --single-run",
"watch": "karma start"
},
"version": "1.0.4"
"version": "1.0.5"
}
13 changes: 13 additions & 0 deletions spec/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe("scrollToFragment", function (this: { history: History }) {
<a href="other.html#top" id="other" onclick="return false">Other page</a>
<a href="index.html#bottom10400" id="same" onclick="return false">Same page</a>
<a href="#bottom10400" id="hashOnly">Hash only</a>
<a href="#bottom10400"><span id="spanInA">Nested</span></a>
`
);
history.replaceState(null, null, "index.html");
Expand Down Expand Up @@ -81,6 +82,18 @@ describe("scrollToFragment", function (this: { history: History }) {
});
});

describe("clicking an element wrapped by a hash link", () => {
beforeEach((done) => {
scrollToFragment({ scrollIntoView: () => window.scrollTo(0, 123) });
document.getElementById("spanInA").click();
wait(done);
});

it("scrolls, overriding the browser default", () => {
expect(window.scrollY).toBeCloseTo(123, -1);
});
});

describe("without a URL hash", () => {
beforeEach((done) => {
scrollToFragment();
Expand Down
13 changes: 8 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,19 @@ function handleHistoryPush(
}

function handleDocumentClick(event: Event) {
if ((event.target as Node).nodeName !== "A") return;

const anchor = event.target as HTMLAnchorElement;
if (anchor.href.indexOf("#") === -1) return;

const anchor = closestAIncludingSelf(event.target as HTMLElement);
if (!anchor || anchor.href.indexOf("#") === -1) return;
if (anchor.href.replace(/#.*/, "") === location.href.replace(/#.*/, "")) {
throttle(startObserving);
}
}

function closestAIncludingSelf(element?: HTMLElement) {
let target = element;
while (target && target.nodeName !== "A") target = target.parentElement;
return target as HTMLAnchorElement | void;
}

function handleDomMutation() {
throttle(adjustScrollPosition);
}
Expand Down

0 comments on commit bf6ac05

Please sign in to comment.