sutty-base-jekyll-theme/_packs/controllers/menu_controller.js

40 lines
838 B
JavaScript
Raw Normal View History

2021-11-22 17:51:50 +00:00
import { Controller } from "stimulus";
export default class extends Controller {
2021-11-22 17:51:50 +00:00
static targets = ["item"];
2021-11-22 17:51:50 +00:00
connect() {
this.scroll_section_event = this._scroll_section_event.bind(this);
window.addEventListener("scroll:section", this.scroll_section_event);
}
disconnect() {
window.removeEventListener("scroll:section", this.scroll_section_event);
}
_scroll_section_event(event) {
this.update(event.detail.id);
}
2021-11-22 17:51:50 +00:00
get items() {
if (!this._items) {
2021-11-22 17:51:50 +00:00
this._items = {};
for (const item of this.itemTargets) {
2021-11-22 17:51:50 +00:00
this._items[item.href.split("#")[1]] = item;
}
}
2021-11-22 17:51:50 +00:00
return this._items;
}
2021-11-22 17:51:50 +00:00
update(id) {
for (const item of Object.values(this.items)) {
2021-11-22 17:51:50 +00:00
item.classList.remove("active");
}
2021-11-22 17:51:50 +00:00
if (this.items[id]) this.items[id].classList.add("active");
}
}