Recently, I have summarized some common small functions (URL acquisition, URL parameter parsing, Form data parsing, etc.) and the clever use of special reduce method.

1. How to batch hide specified elements?

const hide = (... el) => [...el].forEach((e) => (e.style.display = "none")); / / call the sample hide (document. QuerySelectorAll (" img "));Copy the code

2. How do I check if the element has the specified class?

const hasClass = (el, className) => el.classList.contains(className); // call the example hasClass(document.querySelector(" p.paper "), "special"); // trueCopy the code

3. How do I switch element style classes?

const toggleClass = (el, className) => el.classList.toggle(className); ToggleClass (document.querySelector(" p.stitch "), "special");Copy the code

4. How do I obtain 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, }); // Call the example getScrollPosition(); // {x: 0, y: 100}Copy the code

5. How do I scroll smoothly to the top of the page?

const scrollToTop = () => { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, scrollTop - scrollTop / 8); }}; // Call the example scrollToTop();Copy the code

6. How do I check if the parent element contains child elements?

const elementContains = (parent, child) => parent ! == child && parent.contains(child); // call elementContains(document.querySelector("head"), document.querySelector("title")); // true elementContains(document.querySelector("body"), document.querySelector("body")); // falseCopy the code

7. How to check whether the specified element is visible in the window?

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; }; / / call the sample elementIsVisibleInViewport (el); / / not completely visible elementIsVisibleInViewport (el, true); // Partially visibleCopy the code

8. How do I get all the images in an element?

const getImages = (el, includeDuplicates = false) => { const images = [...el.getElementsByTagName("img")].map((img) => img.getAttribute("src") ); return includeDuplicates ? images : [...new Set(images)]; }; // call example getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...'] getImages(document, false); // ['image1.jpg', 'image2.png', '...']Copy the code

9. How do I determine whether the device is a mobile device or a desktop?

const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? "Mobile" : "Desktop"; DetectDeviceType (); // "mobile" or "desktop"Copy the code

10. How do I get the current URL?

const currentURL = () => window.location.href; // Call the example currentURL();Copy the code

11. Parse URL parameters as objects?

const getURLParameters = (url) => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ( (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a ), {} ); // Call the example getURLParameters("http://url.com/page?n=DevPoint&s=Shenzhen"); // {n: 'DevPoint', s: 'Shenzhen'} getURLParameters("baidu.com"); / / {}Copy the code

12. How do I convert Form data into objects?

const formToObject = (form) => Array.from(new FormData(form)).reduce( (account, [key, value]) => ({ ... account, [key]: value, }), {} ); // call the example formToObject(document.querySelector("#form")); // { city: 'Shenzhen', name: 'DevPoint' }Copy the code

13. Delay function execution (ms)?

const delay = (fn, wait, ... args) => setTimeout(fn, wait, ... args); delay( (text) => { console.log(text); }, 1000, "later" );Copy the code

14. How do I delete DOM events?

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); const fn = () => console.log("!" ); document.body.addEventListener("click", fn); off(document.body, "click", fn);Copy the code

15. How to convert the timestamp to an intuitive time format?

const formatDuration = (ms) => { if (ms < 0) ms = -ms; const time = { day: Math.floor(ms / 86400000), hour: Math.floor(ms / 3600000) % 24, minute: Math.floor(ms / 60000) % 60, second: Math.floor(ms / 1000) % 60, millisecond: Math.floor(ms) % 1000, }; Const timeZh = {day: "day ", hour:" hour ", minute: "minute ", second:" millisecond ", millisecond: "millisecond ",}; return Object.entries(time) .filter((val) => val[1] ! = = 0). The map ((/ key, val) = > ` ${val} ${timeZh [key]} `). Join (", "); }; // Call the example formatDuration(1001); // 1 second, 1 millisecond formatDuration(34325055574); // 397 days, 6 hours, 44 minutes, 15 seconds, 574 millisecondsCopy the code

16. How to obtain the time difference between two dates?

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); GetDaysDiffBetweenDates (new Date("2021-03-20"), new Date("2021-04-03")); / / 14Copy the code

17. How do I copy strings to the clipboard?

const copyToClipboard = (str) => { const el = document.createElement("textarea"); el.value = str; el.setAttribute("readonly", ""); el.style.position = "absolute"; el.style.left = "-9999px"; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand("copy"); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); }}; // Call example copyToClipboard("DevPoint"); // 'DevPoint' copied to clipboard.Copy the code

18. How do I create a counter?

Specify a DOM ID, create a counter, specify the step size, end value, and count at the same frequency.

const counter = (selector, start, end, step = 1, duration = 2000) => { let current = start; const _step = (end - start) * step < 0 ? -step : step; const timer = setInterval(() => { current += _step; document.querySelector(selector).innerHTML = current; if (current >= end) document.querySelector(selector).innerHTML = end; if (current >= end) clearInterval(timer); }, Math.abs(Math.floor(duration / (end - start)))); return timer; }; // Example counter("#counter", 1, 1000, 5, 2000); // Create a counter that starts at 1, steps 5, and counts to 1000Copy the code

After the