Skip to content

Instantly share code, notes, and snippets.

const foo = 'name'
// Detect device
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'mobile'
: 'desktop';
// How2use?
detectDeviceType();
// Take a pics.
const findImages = (el, withDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return withDuplicates ? images : [...new Set(images)];
};
// Examples
findImages(document); // ['image1.jpg', 'image2.png']
findImages(document, true); // ['image1.jpg', 'image1.png']
const scrollTop = () => {
const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollPos > 0) {
window.requestAnimationFrame(scrollTop);
window.scrollTo(0, scrollPos - scrollPos / 8);
}
};
// How2use?
scrollToTop();
body {
background: rgb(204, 204, 204);
font-family: 'Droid Serif', sans-serif;
margin: 0;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
opacity: 1;
}
.details {
// Check if the element contains another element
const contains = (element, child) => element !== child && element.contains(child);
const element = document.querySelector('.parent');
const child = document.querySelector('.child');
contains(element, child); // true | false
// Smooth scroll to top
const scrollTop = () => {
const currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
if (currentPosition > 0) {
window.requestAnimationFrame(scrollTop);
window.scrollTo(0, currentPosition - currentPosition / 8);
}
};
scrollTop();
// Toggle visibility (CSS: .hidden { display: none })
const hide = (els, visibilityClass = 'hidden') => [...els].forEach(el => el.classList.toggle(visibilityClass));
// Example: hide all img elements
hide(document.querySelectorAll('img'));
// Remove property from object with rest
const data = { id: 1, name: 'overment', www: 'overment.com' }
const { ['www']: removed, ...rest} = data;
console.log(rest);
// Inspiration from: Todd Motto
// Rename object keys
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] },
}),
{}
);