vijay khamitkar
Vj's Blog

Follow

Vj's Blog

Follow
Javascript utility for daily work

Photo by Pankaj Patel on Unsplash

Javascript utility for daily work

vijay khamitkar's photo
vijay khamitkar
·Sep 22, 2022·

2 min read

Play this article

Convert NaN to 0 in JavaScript

n = n || 0;
n = n ? n : 0;
n = +n || 0;
function getNumVal(val) {
    if (isNaN(val)) {
      return 0;
    }
    return val;
 }

Handling TypeError: Cannot read properties of undefined (reading x)

function myFunc(a) {
    if (a !== undefined) {
        console.log(a.b);
    }
}

var myVar;
myFunc(myVar);

To extract the string containing in the path of the URL for the location

var path = window.location.pathname; // https://vj2tech.hashnode.dev/javascript-utility-for-daily-work
path = path.split('/');
var nameplate = path[1];  
console.log(nameplate);  // javascript-utility-for-daily-work

Find the number of days between two dates

const dateDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

console.log(dateDiff)

Generate a Random Integer within the given range with Math.random function

const randomNumber = (min, max) => Math.floor(Math.random() * (max - min)) + min;

randomNumber(1, 5);    // 4

Wait for an element (class or Id) to load in Dom and then trigger the function

@{String} querySelector - Selector of element to wait for loading

@{Integer} timeout - Milliseconds to wait before timing out, or 0 for no timeout


function waitForElementtoLoad(querySelector, timeout){
    return new Promise((resolve, reject)=>{
      var timer = false;
      if(document.querySelectorAll(querySelector).length) return resolve();
      const observer = new MutationObserver(()=>{
        if(document.querySelectorAll(querySelector).length){
          observer.disconnect();
          if(timer !== false) clearTimeout(timer);
          return resolve();
        }
      });
      observer.observe(document.body, {
        childList: true, 
        subtree: true
      });
      if(timeout) timer = setTimeout(()=>{
        observer.disconnect();
        reject();
      }, timeout);
    });
  }

  waitForElementtoLoad("#dropdown-label-1", 4000).then(function(){
      alert("element is loaded.. do stuff");
  }).catch(()=>{
      alert("element did not load in 4 seconds");
  });

Did you find this article valuable?

Support vijay khamitkar by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this