Skip to content

Instantly share code, notes, and snippets.

@morsecodemedia
Created November 3, 2020 20:23
Show Gist options
  • Save morsecodemedia/23235ed5b5fdb876c759e53072c0b627 to your computer and use it in GitHub Desktop.
Save morsecodemedia/23235ed5b5fdb876c759e53072c0b627 to your computer and use it in GitHub Desktop.
import { animatedScrollTo } from 'es6-scroll-to'
import { easeInOutQuad } from 'es6-easings'
class Utils {
constructor () {
this.queryString = {}
let query = window.location.search.substring(1)
let vars = query.split('&')
vars.map(v => {
var pair = v.split('=')
if (typeof this.queryString[pair[0]] === 'undefined') {
this.queryString[pair[0]] = decodeURIComponent(pair[1])
} else if (typeof this.queryString[pair[0]] === 'string') {
var arr = [ this.queryString[pair[0]], decodeURIComponent(pair[1]) ]
this.queryString[pair[0]] = arr
} else {
this.queryString[pair[0]].push(decodeURIComponent(pair[1]))
}
})
Array.from(document.querySelectorAll('.back-to-top')).map(el => {
el.addEventListener('click', e => {
this.scrollToElement('#top')
e.preventDefault()
})
})
}
closest (elem, selector) {
for (; elem && elem !== document; elem = elem.parentNode) {
if (elem.matches(selector)) return elem
}
return null
}
getParamByName (name) {
return this.queryString[name]
}
getAudience () {
if (document.querySelector('body').classList.contains('hcp')) {
return 'hcp'
} else {
return 'pat'
}
}
debounce (context, callback, wait) {
let timeout
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => callback.apply(context, args), wait)
}
}
scrollTo (distance) {
animatedScrollTo(distance)
}
scrollToElement (selector, shift) {
let el
try {
el = document.querySelector(selector)
} catch (e) {
el = document.body
}
if (el) {
if (!shift) {
shift = 0
}
var offset = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top
offset -= shift
this.scrollTo({
to: parseInt(offset, 10),
duration: 800,
easing: easeInOutQuad
})
}
}
isScrolledIntoView (el) {
var rect = el.getBoundingClientRect()
var elemTop = rect.top
var elemBottom = rect.bottom
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight)
return isVisible
}
live (eventType, elementQuerySelector, cb) {
document.addEventListener(eventType, function (event) {
var qs = document.querySelectorAll(elementQuerySelector)
if (qs) {
var el = event.target; var index = -1
while (el && ((index = Array.prototype.indexOf.call(qs, el)) === -1)) {
el = el.parentElement
}
if (index > -1) {
cb.call(el, event)
}
}
})
}
}
export default new Utils()
/* vi: set shiftwidth=2 tabstop=2 expandtab: */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment