Skip to content

Commit

Permalink
feat: work for links with current page path
Browse files Browse the repository at this point in the history
  • Loading branch information
colinmeinke committed Mar 26, 2018
1 parent 5b356ed commit 99f5b0d
Showing 1 changed file with 28 additions and 8 deletions.
36 changes: 28 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@ const easeInOutQuint = (t, b, _c, d) => {
}
}

const hash = x => {
if (x.indexOf('#') !== -1) {
const [ url, id ] = x.split('#')

return {
url: url !== '' ? url : undefined,
id
}
}
}

const scrollTo = (target, {
duration = 2000,
ease = easeInOutQuint,
Expand Down Expand Up @@ -50,16 +61,25 @@ const init = ({

els.map(el => {
const href = el.getAttribute('href')
const duration = parseInt(el.dataset.duration || defaultDuration, 10)

if (href && href.indexOf('#') === 0) {
const id = href.substring(1)
const target = document.getElementById(id)
if (href) {
const { url, id } = hash(href)

if (id && (
!url ||
url === window.location.pathname ||
url === `${window.location.origin}${window.location.pathname}`
)) {
const target = document.getElementById(id)
const duration = parseInt(el.dataset.duration || defaultDuration, 10)

el.addEventListener('click', e => {
e.preventDefault()
scrollTo(target, { duration, ease, offset, callback })
})
if (target) {
el.addEventListener('click', e => {
e.preventDefault()
scrollTo(target, { duration, ease, offset, callback })
})
}
}
}
})
}
Expand Down

0 comments on commit 99f5b0d

Please sign in to comment.