DEV Community

Cover image for 5 most useful JavaScript Utilities!
Haroon Ahmad
Haroon Ahmad

Posted on • Updated on

5 most useful JavaScript Utilities!

Hi, I'm Haroon, a Senior Full Stack Developer. Today, I'll share some incredibly useful JavaScript functions that you can use in almost every project

1. Tracks the visibility of an element within the viewport

This utility uses the Intersection Observer API to track the visibility of an element within the viewport. It calls a callback function with a boolean value indicating whether the element is visible or not.

function onVisibilityChange(element, callback) {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => callback(entry.isIntersecting));
  });
  observer.observe(element);
}

// Example usage:
const targetElement = document.querySelector('#target');
onVisibilityChange(targetElement, (isVisible) => {
  console.log(`Element is ${isVisible ? 'visible' : 'not visible'}`);
});
Enter fullscreen mode Exit fullscreen mode

2. Reactive viewport breakpoints

This utility allows you to define breakpoints and get notified when the viewport width crosses these breakpoints. It calls a callback function with the current breakpoint value.

function onBreakpointChange(breakpoints, callback) {
  const mediaQueries = breakpoints.map(bp => window.matchMedia(`(max-width: ${bp}px)`));

  function checkBreakpoints() {
    const breakpoint = breakpoints.find((bp, i) => mediaQueries[i].matches);
    callback(breakpoint || 'default');
  }

  mediaQueries.forEach(mq => mq.addListener(checkBreakpoints));
  checkBreakpoints();
}

// Example usage:
onBreakpointChange([600, 900, 1200], (breakpoint) => {
  console.log(`Current breakpoint: ${breakpoint}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Reactive Clipboard API

This utility listens to copy events and reads the copied text from the clipboard, calling a callback function with the copied text.

function onClipboardChange(callback) {
  document.addEventListener('copy', async () => {
    const text = await navigator.clipboard.readText();
    callback(text);
  });
}

// Example usage:
onClipboardChange((text) => {
  console.log(`Copied text: ${text}`);
});
Enter fullscreen mode Exit fullscreen mode

4. Reactive Screen Orientation API

This utility listens to changes in screen orientation and calls a callback function with the current orientation type.

function onOrientationChange(callback) {
  window.addEventListener('orientationchange', () => {
    callback(screen.orientation.type);
  });
}

// Example usage:
onOrientationChange((orientation) => {
  console.log(`Current orientation: ${orientation}`);
});
Enter fullscreen mode Exit fullscreen mode

5. Reactive state to show whether the mouse leaves the page

This utility tracks when the mouse leaves or enters the page and calls a callback function with a boolean value indicating whether the mouse has left the page.

function onMouseLeavePage(callback) {
  document.addEventListener('mouseleave', () => {
    callback(true);
  });

  document.addEventListener('mouseenter', () => {
    callback(false);
  });
}

// Example usage:
onMouseLeavePage((hasLeft) => {
  console.log(`Mouse has ${hasLeft ? 'left' : 'entered'} the page`);
});
Enter fullscreen mode Exit fullscreen mode

Each of these utilities leverages event listeners and modern APIs to provide reactive behavior in your JavaScript applications.

Thank you for taking the time to explore these powerful JavaScript utilities with me. I hope you find them as useful and exciting as I do. Feel free to experiment with these functions in your projects and see how they can enhance your development process. If you have any questions or want to share your own tips, please write down in comments. Happy coding!

Top comments (0)