Skip to content

Instantly share code, notes, and snippets.

View electerious's full-sized avatar

Tobias Reich electerious

View GitHub Profile
const decodeHTML = (str) => {
const elem = document.createElement('div')
elem.innerHTML = str
return (elem.childNodes.length===0 ? '' : elem.childNodes[0].nodeValue)
}
@electerious
electerious / nicetry.js
Last active July 30, 2016 14:47
Try to execute a function and discard any error that occurs
const nicetry = (fn) => {
try { return fn() }
catch (e) {}
}
const hasTouchscreen = () => {
const mobileDevice = (/Android|iPhone|iPad|iPod/i).test(navigator.userAgent || navigator.vendor || window.opera)
const onTouchEnd = ('ontouchend' in document.documentElement)
return (mobileDevice && onTouchEnd)
}
@electerious
electerious / debounce.js
Last active December 12, 2018 08:18 — forked from jasonwyatt/debouncer.js
How to **correctly** debounce an event that will be triggered many times with identical arguments.
const debounce = function(fn, duration) {
let timeout = null
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => fn(...args), duration)
@electerious
electerious / select.js
Last active January 24, 2017 09:04
Select multiple elements and receive an array
const select = (query, elem = null) => {
elem = (elem==null ? document : elem)
let elems = elem.querySelectorAll(query)
if (elems==null) return []
else return Array.prototype.slice.call(elems, 0)
}
@electerious
electerious / toggler.js
Last active January 24, 2017 09:04
Toggle between true and false
const toggler = (initState) => {
initState = initState!==false
let state = initState
return {
get : () => state,
reset : () => state = initState,
toggle : () => state = !state,
@electerious
electerious / counter.js
Last active January 24, 2017 09:04
Count up and down between two numbers
const counter = (min, max, initial) => {
let index = initial - min
let length = max - min + 1
return (modifier = 0) => {
index = (index + modifier) % length
if (index>=0) index = 0 + index
@electerious
electerious / limit.js
Created November 13, 2015 10:45
Limit a number between a min and max value
const limit = (min, max, num) => Math.min(Math.max(num, min), max)
@electerious
electerious / stopEvent.js
Last active January 24, 2017 09:04
Stop event propagation and prevent the default
const stopEvent = (e = {}) => {
if (typeof e.stopPropagation==='function') e.stopPropagation()
if (typeof e.preventDefault==='function') e.preventDefault()
}
@electerious
electerious / scrollroot.js
Last active September 17, 2019 13:45
Cross-browser scroll element fetching
const scrollroot = (() => {
if ('scrollingElement' in document) return document.scrollingElement
const initial = document.documentElement.scrollTop
document.documentElement.scrollTop = initial + 1
const updated = document.documentElement.scrollTop
document.documentElement.scrollTop = initial