Commonly Used JavaScript Functions You Need to Know
This article collects functions that are very commonly used in daily development, some may be complicated, some may be simple, but I believe it will be more or less helpful to everyone.
Generate random colors
Does your website need to generate random colors? The following line of code will do it.
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}` console.log(generateRandomHexColor())
Array reordering
Reordering the elements of an array is a very important skill, but there is no such function in native Array.
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5) const arr = [1, 2, 3, 4, 5] console.log(shuffle(arr))
Copy to clipboard
Copy to clipboard is a very useful function that improves user convenience.
const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text) copyToClipboard("Hello World!")
Detect dark theme
The dark theme is becoming more and more popular, and many users will enable the case mode in the device. We can improve the user experience by switching the application to the dark theme.
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches; console.log(isDarkMode())
scroll to top
The easiest way to scroll an element to the top is to use scrollIntoView. Set block to start to scroll to the top; set behavior to smooth to enable smooth scrolling.
javascript copy code const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
scroll to bottom
Like scrolling to the top, scrolling to the bottom only needs to set the block to end.
javascript copy code const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
Check if element is on screen
The best way to check if an element is in the window is to use IntersectionObserver.
javascript copy code const callback = (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { // `entry.target` is the dom element console.log(`${entry.target.id} is visible`); } }); }; const options = { threshold: 1.0, }; const observer = new IntersectionObserver(callback, options); const btn = document.getElementById("btn"); const bottomBtn = document.getElementById("bottom-btn"); observer.observe(btn); observer.observe(bottomBtn);
Testing Equipment
Use navigator.userAgent to detect which platform device the website is running on.
javascript copy code const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? "Mobile" : "Desktop"; console.log(detectDeviceType());
Hidden element
We can set the element's style.visibility to hide the element's visibility, but the element's space will still be occupied. If an element's style.display is set to none, the element will be removed from the rendering stream.
javascript copy code const hideElement = (el, removeFromFlow = false) => { removeFromFlow ? (el.style.display = 'none') : (el.style.visibility = 'hidden') }
Get parameters from URL
There is a URL object in JavaScript, through which the parameters in the URL can be obtained very conveniently.
javascript copy code const getParamByUrl = (key) => { const url = new URL(location.href) return url.searchParams.get(key) }
deep copy object
Deep copying an object is very simple, first convert the object to a string, and then convert it to an object.
javascript copy code const deepCopy = obj => JSON.parse(JSON.stringify(obj))
In addition to the API utilizing JSON, there is a newer structuredClone API for deep copying objects, but not all browsers support it.
javascript copy code structuredClone(obj)
Thank you for reading.