Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 20, 2022 05:39 am GMT

6 Killer Utility Functions in JavaScript

This is somewhat of an extension to last week's 7 Killer One-Liners in JavaScript. If you haven't already read the article, you are highly encouraged to do so.

1. Check if an element is visible in the viewport

IntersectionObserver is a great way to check if an element is visible in the viewport.

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);

You can customize the behavior of the observer using the option parameter. threshold is the most useful attribute, it defines the percentage of the element that needs to be visible in the viewport for the observer to trigger.

2. Detect device

You can use the navigator.userAgent to gain minute insights and detect the device running the application

const detectDeviceType = () =>  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(    navigator.userAgent  )    ? "Mobile"    : "Desktop";console.log(detectDeviceType());

3. Hide elements

You can just toggle the visibility of an element using the style.visibility property and in case you want to remove it from the render flow, you can use the style.display property.

const hideElement = (element, removeFromFlow = false) => {  removeFromFlow    ? (element.style.display = "none")    : (element.style.visibility = "hidden");};

If you don't remove an element from the render flow, it will be hidden, but its space will still be occupied. It is highly useful while rendering long lists of elements, the elements NOT in view (can be tested using IntersectionObserver) can be hidden to provide a performance boost.

4. Get the parameters from the URL

JavaScript makes fetching the parameters from any address a walk in the park using the URL object.

const url = new URL(window.location.href);const paramValue = url.searchParams.get("paramName");console.log(paramValue);

5. Deep copy an object with ease

You can deep copy any object by converting it to a string and back to an object.

const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));

6. wait function

JavaScript does ship with a setTimeout function, but it does not return a Promise object, making it hard to use in async functions. So we have to write our own wait/sleep function.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));const asyncFunc = async () => {  await wait(1000);  console.log("async");};asyncFunc();

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas

Original Link: https://dev.to/ruppysuppy/6-killer-utility-functions-in-javascript-1j68

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To