10 Modern ES6 Code Snippets to Solve Practical JavaScript Problems
Here I have hand-picked some of the most useful code snippets. In this article I tried to sort them based on their practical use, answering common questions you may face in your project:
1.How to hide all elements specified?
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
// Example
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
2.How to check if the element has the specified class?
const hasClass = (el, className) => el.classList.contains(className);
// Example
hasClass(document.querySelector('p.special'), 'special'); // true
3.How to toggle a class for an element?
const toggleClass = (el, className) => el.classList.toggle(className);
// Example
toggleClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymore
4.How to get the scroll position of the current page?
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// Example
getScrollPosition(); // {x: 0, y: 200}
5.How to smooth-scroll to the top of the page?
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// Example
scrollToTop();
6.How to check if the parent element contains the child element?
const elementContains = (parent, child) => parent !== child && parent.contains(child);
// Examples
elementContains(document.querySelector('head'), document.querySelector('title'));
// true
elementContains(document.querySelector('body'), document.querySelector('body')); // false
7.How to check if the element specified is visible in the viewport?
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// Examples
elementIsVisibleInViewport(el); // (not fully visible)
elementIsVisibleInViewport(el, true); // (partially visible)
8.How to fetch all images within an element?
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
// Examples
getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false); // ['image1.jpg', 'image2.png', '...']
9.How to figure out if the device is a mobile device or a desktop/laptop?
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
// Example
detectDeviceType(); // "Mobile" or "Desktop"
10.How to get the current URL?
const currentURL = () => window.location.href;
// Example
currentURL(); // 'https://google.com'
To get like these tips and tricks, stay with me. Thanks for reading.