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?
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);
}
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);
}
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