const isBrowser = typeof window === 'object' && typeof document === 'object'
const touchSupported = () => {
'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch)
}
const hasClass = (el, className) => el.classList.contains(className)
const hasAttr = (el, attr) => el.hasAttribute(attr)
const clone = (el) => el.cloneNode(true)
const outside = (ele, evt) => !ele.contains(evt.target) && ele !== evt.target
document.addEventListener('click', function (evt) {
const isClickedOutside = outside(ele, evt)
})
const isFocused = (ele) => ele === document.activeElement
const isDarkMode = () =>
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const isRightClick = (e) => {
e = e || window.event
return 'which' in e ? e.which === 3 : e.button === 2
}
ele.addEventListener('mousedown', function (e) {
const key = isRightClick(e) ? 'right' : 'left'
// e.button === 0: the left button is clicked
// e.button === 1: the middle button is clicked
// e.button === 2: the right button is clicked
// e.button === 3: the `Browser Back` button is clicked
// e.button === 4: the `Browser Forward` button is clicked
})
const result = ele.closest(selector)
// or
const matches = function (ele, selector) {
return (
ele.matches ||
ele.matchesSelector ||
ele.msMatchesSelector ||
ele.mozMatchesSelector ||
ele.webkitMatchesSelector ||
ele.oMatchesSelector
).call(ele, selector)
}
// Find the closest element to `ele` and matches the `selector`
const closest = function (ele, selector) {
let e = ele
while (e) {
if (matches(e, selector)) {
break
}
e = e.parentNode
}
return e
}
const removeAllChildNodes = (parent) => {
while (parent.firstChild) {
parent.removeChild(parent.firstChild)
}
}
// or
const removeAllChildNodes1 = (parent) => {
parent.innerHTML = ''
}
const isVisible = function (ele, container) {
const eleTop = ele.offsetTop
const eleBottom = eleTop + ele.clientHeight
const containerTop = container.scrollTop
const containerBottom = containerTop + container.clientHeight
// The element is fully visible in the container
return (
(eleTop >= containerTop && eleBottom <= containerBottom) ||
// Some part of the element is visible in the container
(eleTop < containerTop && containerTop < eleBottom) ||
(eleTop < containerBottom && containerBottom < eleBottom)
)
}