Skip to content

Instantly share code, notes, and snippets.

@ntnyq
Last active April 23, 2020 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntnyq/0cbadbd47e1086d77039d7d15517a40b to your computer and use it in GitHub Desktop.
Save ntnyq/0cbadbd47e1086d77039d7d15517a40b to your computer and use it in GitHub Desktop.
[JavaScript Utils] #Utils
const cache = (() => {
const store = {}
return ({
set (key, value) {
store[key] = value
},
has (key) {
return !!this.get(key)
},
get (key) {
return store[key]
},
remove (key) {
if (this.has(key)) {
store[key] = null
delete store[key]
}
},
})
})()
console.log(cache)
cache.set('name', 'ntnyq')
console.log(cache.get('name'))
console.log(cache.has('name'))
cache.remove('name')
console.log(cache.has('name'))
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector
}
// closest
export const closest = (el, selector) => {
let element = el
while (element && element.matches) {
if (element.matches(selector)) {
return element
}
element = element.parentNode
}
return null
}
// event
export const on = (el, type, handle) => el.addEventListener(type, handle)
export const off = (el, type, handle) => el.removeEventListener(type, handle)
// query
const arrSlice = Array.prototype.slice
export const $ = (selector, context = document) => context.querySelector(selector)
export const $$ = (selector, context = document) =>
arrSlice.call(context.querySelectorAll(selector))
const indexOf = Array.prototype.indexOf
export const nodeIndex = node => indexOf.call(node.parentNode.children, node)
// style
export const style = (el, styles) => {
Object.keys(styles).forEach(name => (el.style[name] = styles[name]))
}
// class
export const addClass = (el, ...classArgs) => el.classList.add(classArgs)
export const removeClass = (el, ...classArgs) => el.classList.remove(classArgs)
// dom operation
export const insertBefore = (node, beforeNode) =>
node.insertAdjacentElement('beforebegin', beforeNode)
export const insertAfter = (node, afterNode) => node.insertAdjacentElement('afterend', afterNode)
export const prepend = (node, preNode) => node.insertAdjacentElement('afterbegin', preNode)
// scrollDirection
export const scrollDirection = el => {
if (el.scrollHeight > el.offsetHeight) return 'y'
if (el.scrollWidth > el.offsetWidth) return 'x'
return null
}
export const prevent = e => e.preventDefault()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment