Skip to content

Commit

Permalink
feat: url link matched (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
simboonlong authored Jun 26, 2022
1 parent 05ae91f commit 01b1c1c
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,4 +317,21 @@ SearchParams.removeAll({ key: "foo" });
// https://example.com/
```

---

#### urlLinkMatched

Scan links and update, when `location.href` URL matched link's href.

Example:

```
import { urlLinkMatched } from "@simboonlong/utility"
urlLinkMatched({
links: document.querySelectorAll("a"),
callback: (link) => link.classList.add("active"),
});
```

Author © [Sim Boon Long](https://simboonlong.com).
16 changes: 16 additions & 0 deletions src/urlLinkMatched.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
interface UrlLinkMatched {
links: NodeListOf<HTMLAnchorElement>;
callback: (link: HTMLAnchorElement) => void;
}

export const urlLinkMatched = ({ links, callback }: UrlLinkMatched): void => {
links.forEach((link) => {
const href = link.getAttribute("href");
if (!href) throw new Error("href attribute not defined on anchor element");

const linkHref = new URL(href, document.baseURI).href;
if (location.href === linkHref) {
callback(link);
}
});
};
32 changes: 32 additions & 0 deletions test/urlLinkMatched.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getByText } from "@testing-library/dom";
import { urlLinkMatched } from "../src/urlLinkMatched";

const getExampleDOM = () => {
const div = document.createElement("div");

const link1 = document.createElement("a");
link1.setAttribute("href", "./");
link1.innerHTML = "home";

const link2 = document.createElement("a");
link2.setAttribute("href", "./about");
link2.innerHTML = "about";

div.appendChild(link1);
div.appendChild(link2);

return div;
};

test("urlLinkMatch should add class correctly", async () => {
const className = "active";
const container = getExampleDOM();
// console.log(prettyDOM(container));

urlLinkMatched({
links: container.querySelectorAll("a"),
callback: (link) => link.classList.add(className),
});

expect(getByText(container, "home").getAttribute("class")).toBe(className);
});

0 comments on commit 01b1c1c

Please sign in to comment.