Skip to content

Instantly share code, notes, and snippets.

View electerious's full-sized avatar

Tobias Reich electerious

View GitHub Profile
escapeHTML = (html = '') => {
// Ensure that html is a string
html += ''
// Escape all critical characters
html = html.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
@electerious
electerious / closest.js
Last active November 6, 2015 22:14
Select the closest matching parent of an element
const closest = (elem, className) => {
if (elem==null || elem.classList==null) return null
return (elem.classList.contains(className) ? elem : closest(elem.parentNode, className))
}
const decodeHTML = (str) => {
const elem = document.createElement('div')
elem.innerHTML = str
return (elem.childNodes.length===0 ? '' : elem.childNodes[0].nodeValue)
}
@electerious
electerious / hasLocalStorage.js
Last active July 21, 2016 15:33
Detect if browser supports localStorage
const hasLocalStorage = () => {
const tmp = 'tmp'
try {
localStorage.setItem(tmp, tmp)
localStorage.removeItem(tmp)
return true
@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) {}
}
@electerious
electerious / toClassString.js
Created January 21, 2017 15:48
Conditionally convert the keys of an object to a string of class names
const toClassString = (obj) => Object.keys(obj).filter((key) => obj[key]===true).join(' ').trim()
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 / 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 / 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 / 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