D Dev Notebook

JavaScript Code Snippets

JS

JavaScript observer

const observer = new MutationObserver(() => {
  const isTargetPage = document.querySelector('.classname1');
  const hasAlreadyInitialized = document.querySelector('.classname2');

  if (isTargetPage && !hasAlreadyInitialized) {
    console.log('This is the target page');
  } else {
    console.log('This is not the target page');
  }
});

const bodyElement = document.body;
if (bodyElement) { observer.observe(bodyElement, { childList: true, subtree: true })}

Reusable Mutation Observer Function

function waitForElement(selector, callback, options = { subtree: true, childList: true }, timeout = 10000) {
  const observer = new MutationObserver((mutations, obs) => {
    const element = document.querySelector(selector);
    if (element) {
      clearTimeout(timer);
      obs.disconnect();
      callback(element);
    }
  });

  observer.observe(document.body, options);

  const timer = setTimeout(() => {
    observer.disconnect();
    console.warn(`Timeout: Element "${selector}" not found within ${timeout / 1000} seconds.`);
  }, timeout);
}


waitForElement('.class1', (el) => {
  console.log('class1 found:', el);
});

waitForElement('.class2', (el) => {
  console.log('class2 found:', el);
});

Trigger when element is visible to viewport

// Select the element you want to observe
const target = document.querySelector('#myElement');

// Create an observer
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element is visible in the viewport!');
      // You can stop observing if you only want to trigger once
      observer.unobserve(entry.target);
    }
  });
}, {
  threshold: 0.1 // Trigger when at least 10% of the element is visible
});

// Start observing the target
observer.observe(target);

Run the function when user first scroll

function runOnFirstScroll() {
  console.log('User scrolled for the first time!');
}

let hasScrolled = false;
window.addEventListener('scroll', function () {
  if (!hasScrolled) {
    runOnFirstScroll();
    hasScrolled = true;
  }
});

Check if the user's device is a mobile device

const isMobile = /iPhone|Android/i.test(navigator.userAgent);
if(isMobile){
  console.log("User is on a mobile device.");
} else {
  console.log("User is on a desktop or non-mobile device.");
}
if (window.matchMedia("(max-width: 768px)").matches) {
    console.log("mobile screen size");
}else{
    console.log("desktop screen size");
}

Platform (iPhone, iPhone, iPad) Specific

function iOS() {
            return [
                'iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'
                ].includes(navigator.platform)
                // iPad on iOS 13 detection
                || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
        }

        if (iOS()) {
             console.log('iOS Device')
        }

On this page