Member-only story

6 Killer Functions in JavaScript that Made My Life Easier

Tapajyoti Bose
2 min readFeb 20, 2022

--

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

--

--

Tapajyoti Bose
Tapajyoti Bose

Written by Tapajyoti Bose

Top Rated Freelancer || Blogger || Cross-Platform App Developer || Web Developer || Open Source Contributor || FIRE Enthusiast

Responses (11)