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
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.
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.
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.
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 returnstrue
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With