10 modern ES6 code snippets to solve practical JS problems

I hand-picked some of the most useful code snippets from 30 seconds of code. It’s an awesome resource, go ahead and show it some ❤️.

In this article I tried to sorted them based on their practical use, answering common questions you may face in your p…


This content originally appeared on DEV Community and was authored by Saymon Tavares

I hand-picked some of the most useful code snippets from 30 seconds of code. It's an awesome resource, go ahead and show it some ❤️.

In this article I tried to sorted 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'

I hope you enjoyed the read!

Feel free to follow me on GitHub, LinkedIn and DEV for more!


This content originally appeared on DEV Community and was authored by Saymon Tavares


Print Share Comment Cite Upload Translate Updates
APA

Saymon Tavares | Sciencx (2021-08-11T19:28:30+00:00) 10 modern ES6 code snippets to solve practical JS problems. Retrieved from https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/

MLA
" » 10 modern ES6 code snippets to solve practical JS problems." Saymon Tavares | Sciencx - Wednesday August 11, 2021, https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/
HARVARD
Saymon Tavares | Sciencx Wednesday August 11, 2021 » 10 modern ES6 code snippets to solve practical JS problems., viewed ,<https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/>
VANCOUVER
Saymon Tavares | Sciencx - » 10 modern ES6 code snippets to solve practical JS problems. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/
CHICAGO
" » 10 modern ES6 code snippets to solve practical JS problems." Saymon Tavares | Sciencx - Accessed . https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/
IEEE
" » 10 modern ES6 code snippets to solve practical JS problems." Saymon Tavares | Sciencx [Online]. Available: https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/. [Accessed: ]
rf:citation
» 10 modern ES6 code snippets to solve practical JS problems | Saymon Tavares | Sciencx | https://www.scien.cx/2021/08/11/10-modern-es6-code-snippets-to-solve-practical-js-problems/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.