Skip to content

Commit

Permalink
Fix lingering active class
Browse files Browse the repository at this point in the history
Modified behavior of getSectionInView(), onScroll(), and removeCurrentActive() to remove active class on first menu item when that item corresponds to a section below other content
  • Loading branch information
sulliops committed Jun 26, 2024
1 parent 6d05d54 commit b0efc4f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion demo/dist/simple-scrollspy.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions src/scrollspy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ export class ScrollSpy {
this.removeCurrentActive({ ignore: menuItem })
this.setActive(menuItem)
}
} else {
this.removeCurrentActive({ ignore: null })
}
}

Expand Down Expand Up @@ -125,7 +127,10 @@ export class ScrollSpy {
}

const isInView = currentPosition > startAt && currentPosition <= endAt
if (isInView) return this.sections[i]
if (isInView) {
if (!startAt) return false
return this.sections[i]
}
}
}

Expand All @@ -139,10 +144,10 @@ export class ScrollSpy {
}
}

removeCurrentActive({ ignore }: { ignore: HTMLElement }) {
removeCurrentActive({ ignore }: { ignore: HTMLElement | null }) {
if (this.menuList) {
const { hrefAttribute, menuActiveTarget, activeClass } = this.options
const items = `${menuActiveTarget}.${activeClass}:not([${hrefAttribute}="${ignore.getAttribute(hrefAttribute)}"])`
const items = ignore ? `${menuActiveTarget}.${activeClass}:not([${hrefAttribute}="${ignore.getAttribute(hrefAttribute)}"])` : `${menuActiveTarget}.${activeClass}`
const menuItems = this.menuList.querySelectorAll(items)

menuItems.forEach((item) => item.classList.remove(this.options.activeClass))
Expand Down

0 comments on commit b0efc4f

Please sign in to comment.