Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Feature detection for One Javascript Feature (intersectionObserver)

Is there a way of storing a built-in javascript method in a variable to set different behaviour for when this method isn't available in certain browsers?

My specific case is for intersectionObserver which isn't available in Safari or older MS browsers. I have some animations triggered by this and would like to turn them off if intersectionObserver isn't available.

what I want to do essentially this:

var iO = intersectionObserver;

if ( !iO ) {
 // set other defaults
}

I don't really want to load a polyfill or library for just one feature?

Many thanks

Emily

like image 296
The Chewy Avatar asked Feb 14 '18 18:02

The Chewy


People also ask

What is IntersectionObserver in Javascript?

The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount.

What is rootMargin IntersectionObserver?

The IntersectionObserver interface's read-only rootMargin property is a string with syntax similar to that of the CSS margin property. Each side of the rectangle represented by rootMargin is added to the corresponding side in the root element's bounding box before the intersection test is performed.

What is isIntersecting?

isIntersecting. The IntersectionObserverEntry interface's read-only isIntersecting property is a Boolean value which is true if the target element intersects with the intersection observer's root.


1 Answers

The in Operator is widely used to detect features supported by the browser. JavaScript features are globally available as a property to window object. So we can check if window element has the property.

if("IntersectionObserver" in window){
    /* work with IntersectionObserver */
}
if("FileReader" in window){
    /* work with FileReader */
}

The in operator returns true if the specified property is in the specified object or its prototype chain.
Syntax: prop in object
[source: developer.mozilla.org]

So you can also save the result in a boolean variable and use it later in your code.

var iO = "IntersectionObserver" in window; /* true if supported */

if ( !iO ) {
 // set other defaults
}
like image 108
Munim Munna Avatar answered Sep 17 '22 19:09

Munim Munna