Skip to content

Commit

Permalink
Merge pull request #150 from okTurtles/sebin/task/#121-broken-arrow-i…
Browse files Browse the repository at this point in the history
…n-about-us

#121 - Fix the error in the arrow button in /about-us
  • Loading branch information
taoeffect authored Sep 2, 2024
2 parents 39bc576 + 10d782e commit a5cf39a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/pages/about-us.astro
Original file line number Diff line number Diff line change
Expand Up @@ -136,22 +136,20 @@ import { resolvePath } from '@/utils/helpers.js'
</Layout>

<script>
addEventListener("DOMContentLoaded", () => {
setTimeout(attachEventHandlers, 100)

function attachEventHandlers () {
const scrollDownBtn = document.body.querySelector('#scroll-down-btn')

scrollDownBtn && scrollDownBtn.addEventListener('click', () => {
const scrollToEl = document.querySelector('#scroll-down-to')

scrollToEl && scrollToEl.scrollIntoView({
import { waitForElement } from '@/utils/helpers'

waitForElement(
['#scroll-down-btn', '#scroll-down-to'],
(els: Array<any>) => {
const [arrowBtnEl, scrollTargetEl] = els
arrowBtnEl.addEventListener('click', () => {
scrollTargetEl.scrollIntoView({
behavior: 'smooth',
block: 'center'
})
})
}
})
)
</script>

<style lang="scss">
Expand Down
53 changes: 53 additions & 0 deletions src/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,56 @@ export function validateEmail (email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
return emailRegex.test(email)
}

export function waitForElement(
selectors,
handler,
timeout = 100,
expiry = 5000
) {
// Recursively document.querySelector('...') the passed selector(s) until,
//
// 1) They are found in DOM and returned.
// 2) expiry duration.
//
// NOTE: This method was created to cope with the cases where <script>..</script> in .astro files
// somehow get exceuted well ahead of time before the DOM rendering is completed.

let intervalIds = {}
let localSelectors = []
let foundEls = []
const passToHandler = () => {
if (!foundEls.length) { handler(null) }

handler(Array.isArray(selectors) ? foundEls : foundEls[0])
}

if (Array.isArray(selectors)) {
localSelectors = selectors
} else {
localSelectors.push(selectors)
}

localSelectors.filter(Boolean)
.forEach((selector, index) => {
intervalIds[selector] = setInterval(() => {
const foundEl = document.querySelector(selector)

if (foundEl) {
clearInterval(intervalIds[selector])
delete intervalIds[selector]

foundEls[index] = foundEl
if (Object.keys(intervalIds).length === 0) {
passToHandler()
}
}
}, timeout)
})

setTimeout(() => {
Object.values(intervalIds).forEach(intervalId => {
clearInterval(intervalId)
})
}, expiry)
}

0 comments on commit a5cf39a

Please sign in to comment.