Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to test for scrollIntoView browser compatibility?

I am looking for a way to do a real-time test for scrollIntoView functionality of my user's browser. This is not a "caniuse" check; rather I want to have graceful degradation. I am using jQuery, and would like to use a preventDefault() if scrollIntoView is functional.

I started with:

        if (window.scrollIntoView) {
            e.preventDefault();
            $('p#result').text('scrollIntoView is available');
        } else {
            $('#result').text('scrollIntoView is not available');
        }

but I see that window.scrollIntoView is undefined in the inspector. However, because scrollIntoView works (in my version of Chrome and FireFox), it shouldn't be undefined. What other options can I have to see if it the user's browser supports the function?

like image 713
Sablefoste Avatar asked Oct 24 '17 20:10

Sablefoste


2 Answers

I found that at least for the WaterFox browser (and likely a few more), scrollBehavior did exist in document.documentElement.style as Stefan van de Vooren suggests, yet the browser would throw the following error:

TypeError: 'block' member of ScrollIntoViewOptions 'center' is not a valid 
value for enumeration ScrollLogicalPosition.

A simple try-catch statement solved the issue for us:

try {
   element.scrollIntoView({
     behavior: "smooth",
     block: "center"
   });
} catch (error) {
   //fallback to prevent browser crashing
   element.scrollIntoView(false);
}
like image 121
Drew Jex Avatar answered Sep 22 '22 12:09

Drew Jex


It could also be handy to check if scrollIntoView only support boolean true / false or also supports behaviour for smooth scrolling.

var isSmoothScrollSupported = 'scrollBehavior' in document.documentElement.style;
if(isSmoothScrollSupported) {
    element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});    
} else {
    element.scrollIntoView(false);
}
like image 44
Stefan van de Vooren Avatar answered Sep 20 '22 12:09

Stefan van de Vooren