19 Practical ES6 Code Snippets to Solve Common JavaScript Problems

In our development process, we often encounter challenging problems that may only require a few lines of code to solve. In this article, I tried to compile some useful code snippets to help you make it easier when dealing with URLs, DOM, events, dates, user preferences, etc.

All these code snippets are carefully selected from "30 seconds of code". This is a great resource and I highly recommend checking out more.

The main criterion by which these code snippets were screened was practicality. Hopefully you'll find something valuable that you can apply to future codebases.

1. How to hide all specified elements?

const hide = (...el) => [...el].forEach(e => (e.style.display = "none"));

// Example
hide(document.querySelectorAll("img"));  // 隐藏页面上所有<img />元素

2. How to confirm whether an element has the specified class?

const hasClass = (el, className) => el.classList.contains(className); 

// Example 
hasClass(document.querySelector("p.special"), "special"); // true

3. How to switch the class of an element?

const toggleClass = (el, className) => el.classList.toggle(className); 

// Example 
toggleClass(document.querySelector( p.special ),  special ); // 该段不再有 "special" 类

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 scroll to the top of the page for evaluation?

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 confirm whether the parent element contains child elements?

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 confirm whether the specified element 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); // (不完全可见) 
elementIsVisibleInViewport(el, true); // (部分可见)

8. How to get all images within an element?

const getImages = (el, includeDuplicates = false) => {     
    const images = [...el.getElementsByTagName("img")].map(img => img.getAttribute("hide"));     
    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 tell whether a device is a mobile device or a desktop device?

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"

11. How to get the base URL?

const getBaseURL = (url) => url.replace(/[?#].*$/, '')

getBaseURL('http://url.com/page?name=Adam&surname=Smith')
// 'http://url.com/page'

12. How to check if a URL is an absolute path?

const isAbsoluteURL = (str) => /^[a-z][a-z0-9+.-]*:/.test(str)

isAbsoluteURL('https://google.com') // true
isAbsoluteURL('ftp://www.myserver.net') // true
isAbsoluteURL('/foo/bar') // false

13. How to convert URL parameters into objects?

const getURLParameters = (url) =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  )

getURLParameters('google.com') // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith')
// {name: 'Adam', surname: 'Smith'}

14. How to check if an element contains another element?

const elementContains = (parent, child) =>
  parent !== child && parent.contains(child)

elementContains(document.querySelector('head'), document.querySelector('title'))
// true
elementContains(document.querySelector('body'), document.querySelector('body'))
// false

15. How to get all ancestor elements of an element?

const getAncestors = (el) => {
  let ancestors = []
  while (el) {
    ancestors.unshift(el)
    el = el.parentNode
  }
  return ancestors
}

getAncestors(document.querySelector('nav'))
// [document, html, body, header, nav]

16. How to smoothly scroll into element view?

const smoothScroll = (element) =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth',
  })

smoothScroll('#fooBar') // 平滑滚动到id为fooBar的元素
smoothScroll('.fooBar')
// 平滑滚动到class为fooBar的第一个元素

17. How to handle click event outside the element?

const onClickOutside = (element, callback) => {
  document.addEventListener('click', (e) => {
    if (!element.contains(e.target)) callback()
  })
}

onClickOutside('#my-element', () => console.log('Hello'))
// 当用户点击#my-element外部时将输出'Hello'

18. How to generate UUID?

const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  )

UUIDGeneratorBrowser() // '7982fcfe-5721-4632-bede-6000885be57d'

19. How to get selected text?

const getSelectedText = () => window.getSelection().toString()

getSelectedText() // 'Lorem ipsum'

20. How to copy text to clipboard?

const copyToClipboard = (str) => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str)
  return Promise.reject('The Clipboard API is not available.')
}

21. How to add styles to HTML elements?

const addStyles = (el, styles) => Object.assign(el.style, styles)

addStyles(document.getElementById('my-element'), {
  background: 'red',
  color: '#ffff00',
  fontSize: '3rem',
})

12. How to switch to full screen mode?

const fullscreen = (mode = true, el = 'body') =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen()

fullscreen() // 将body以全屏模式打开
fullscreen(false) // 退出全屏模式

23. How to detect if Caps Lock is on?

<form>
  <label for="username">Username:</label>
  <input
    id="username"
    name="username"
  />

  <label for="password">Password:</label>
  <input
    id="password"
    name="password"
    type="password"
  />
  <span
    id="password-message"
    style="display: none"
    >Caps Lock is on</span
  >
</form>
const el = document.getElementById('password')
const msg = document.getElementById('password-message')

el.addEventListener('keyup', (e) => {
  msg.style = e.getModifierState('CapsLock')
    ? 'display: block'
    : 'display: none'
})

24. How to check if a date is valid?

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf())

isDateValid('December 17, 1995 03:24:00') // true
isDateValid('1995-12-17T03:24:00') // true
isDateValid('1995-12-17 T03:24:00') // false
isDateValid('Duck') // false
isDateValid(1995, 11, 17) // true
isDateValid(1995, 11, 17, 'Duck') // false
isDateValid({}) // false

How to get time (with colon) from date?

const getColonTimeFromDate = (date) => date.toTimeString().slice(0, 8)

getColonTimeFromDate(new Date()) // '08:38:00'

26. How to generate UNIX timestamp from date?

const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000)

getTimestamp() // 1602162242

27. How to check the current user's preferred language?

const detectLanguage = (defaultLang = 'en-US') =>
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang

detectLanguage() // 'nl-NL'

28. How to check the current user's preferred color scheme?

const prefersDarkColorScheme = () =>
  window &&
  window.matchMedia &&
  window.matchMedia('(prefers-color-scheme: dark)').matches

prefersDarkColorScheme() // true

29. How to check if the device supports touch events?

const supportsTouchEvents = () => window && 'ontouchstart' in window

supportsTouchEvents() // true

Get the National Day avatar now

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/133191648