Home >Web Front-end >JS Tutorial >JavaScript Snippets That Will Save You Hours of Coding
JavaScript is a powerful language, but writing repetitive code can consume your time. These 10 handy JavaScript snippets will simplify common tasks and boost your productivity. Let’s dive in!
Easily determine if an element is visible within the viewport:
const isInViewport = (element) => { const rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); };
Quickly copy text to the clipboard without using external libraries:
const copyToClipboard = (text) => { navigator.clipboard.writeText(text); };
Randomize the order of elements in an array with this one-liner:
const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);
Convert a nested array into a single-level array:
const flattenArray = (arr) => arr.flat(Infinity);
Remove duplicates from an array:
const uniqueValues = (array) => [...new Set(array)];
Create a random hex color with ease:
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
Prevent a function from firing too often, ideal for search input:
const debounce = (func, delay) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => func(...args), delay); }; };
Check if a user’s system is in dark mode:
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
A simple snippet to capitalize the first letter:
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
Generate a random number within a range:
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
These snippets are a great way to save time and effort in your JavaScript projects. Bookmark them or integrate them into your personal utility library!
For more JavaScript tips and tricks, check out the original article on Script Binary.
The above is the detailed content of JavaScript Snippets That Will Save You Hours of Coding. For more information, please follow other related articles on the PHP Chinese website!