Detect Unsupported Browsers and Disable animations [duplicate] - javascript

Im not very skilled in javascript so please be bear with me. Safari 6 and below and older android mobile browsers and maybe more do not support the css value VH. My DIV#id or class is not the height of the viewport. Below is a link to a page i found some useful information, but im really not sure how to use it with a css value:
Check whether a css value is supported
Here is the code given as a shortcut for you:
if('opacity' in document.body.style) {
// do stuff
}
function isPropertySupported(property{
return property in document.body.style;
}
In the comments of the link i attached above someone does ask how to check if a css VALUE is supported and the answer is, "You set it, then read the value back and check if the browser retained it." Now im sure that would be useful information if i knew more javascript which i have just started to learn.
This is what i have in mind but im really not sure how to go around doing this.
Check if div#id or div.class has vh css value.
Check whether the css value is supported by the browser.
If its supported then keep loading. If not supported then change id or class.
So to sum up my question:
How do i check if a css value is supported by the browser using javascript or jquery?
Guidance to the answer is really appreciated.
Thanks for your help.

There is the new API CSS.supports. Supported in most browsers except IE.
console.log(
// CSS.supports(property, value)
1, CSS.supports("text-decoration-style", "blink"),
2, CSS.supports("display", "flex"),
3, CSS.supports('--foo', 'red'),
4, CSS.supports('(--foo: red)'),
// CSS.supports(DOMstring)
5, CSS.supports("( transform-origin: 5% 5% )"),
6, CSS.supports("( transform-style: preserve ) or ( -moz-transform-style: preserve ) or "
+ "( -o-transform-style: preserve ) or ( -webkit-transform-style: preserve )")
)
And there is a similar feature in CSS, the #supports feature query selector, also supported in most browsers except IE:
#supports (display: grid) {
div {
display: grid;
}
}
#supports not (display: grid) {
div {
float: right;
}
}

I assume you meant to check whether the vh value is supported, not whether specifically DIV#id bears it?
function cssPropertyValueSupported(prop, value) {
var d = document.createElement('div');
d.style[prop] = value;
return d.style[prop] === value;
}
cssPropertyValueSupported('width', '1px');
// => true
cssPropertyValueSupported('width', '1vh');
// => maybe true, maybe false (true for me)
cssPropertyValueSupported('width', '1foobar');
// => false
EDIT: This is obsolete; CSS.supports is now well supported, and should be used instead. Please support this answer instead.

We can since a while test from javascript if a css rule if available in the context with CSS.supports.
(Since Firefox 22/ Chrome 28)
console.log(
CSS.supports("( transform-origin: 5% 5% )"),
"\n",
CSS.supports("( display: flex )"),
"\n ",
CSS.supports("( background-color: #12233212 )")
)
The CSS.supports() static methods returns a Boolean value indicating
if the browser supports a given CSS feature, or not.
https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports
To go further, we can possibly use this property for browser detection.

I see the code you have there.
var styletotest = "PutStyleHere";
if (styletotest in document.body.style)
{
alert("The " + styletotest + " property is supported");
} else {
alert("The " + styletotest + " property is NOT supported");
}
Simply place the css property you want to test in the quotes where it says
PutStyleHere
And when you load the file it will show a popup telling you if it works or not.
However this seems unnecessary.
Simply Googling:
[property] css W3
where [property] is the property you want to know browser support information.
When I searched
Opacity Css W3
and then clicked on the W3 link... you can scroll down and you will see a section of the page with the info you want like this:
Source

Use the new CSS #supports feature. You can do this from CSS and also from JavaScript.
CSS:
#supports(width: 1vh) {
div#id {
width: 1vh;
}
}
/* Use at `#supports not` if you want to give an `else` condition */
#supports not (width: 1vh) {
div#id {
width: 3%;
}
}
JavaScript way:
The supports() method is provided in the CSS API to do this.
if(CSS.supports('width', '1vh')) {
document.querySelector('div#id').style.width = '1vh';
} else {
documen.querySelector('div#id').style.width = '1%';
}
Read more at CSS Conditional Rules

I'd suggest to use Modernizr.
Modernizr is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them.
Some useful links:
Modernizr: the feature detection library for HTML5/CSS3
Using Modernizr to detect HTML5 features and provide fallbacks
HTML5 Boilerplate custom build of Modernizr for feature detection

This is my code that accounts for totally unsupported properties by checking for presence of camel-Case props in the style, and uses CSS.supports if available.
const prefixes = ['', '-webkit-']
function supports(prop, value) {
if ('CSS' in window && 'supports' in window.CSS) {
for (let i = 0; i < prefixes.length; i++) {
const property = prefixes[i] + prop
if (window.CSS.supports(property, value) ) { return true }
}
return false
}
const el = document.createElement('div')
let found = false
prefixes.forEach((pr) => {
if (found) return
const p = `${pr}${prop}`
const Prop = p.replace(/-(.)/g, (m, s) => s.toUpperCase())
if (!(Prop in el.style)) return
el.style[p] = value
found = el.style[p] == value // can just check if it's not empty actually
})
return found
}

In Chromium browsers starting in version 100 you can now inspect using DevTools to see if a particular declaration (property + value) is supported.
Here is a screenshot of my website using Chrome 101 (Beta), which is the first Chromium version to support the font-palette property:
You can see in the green boxes that the #supports rule with the following conditions:
#supports (font-palette: dark) or (font-palette: light)
that in Chrome 101, both of the following declarations
font-palette: light;
font-palette: dark;
are supported.
Unlike the answers above, this is a pure DevTools -> Styles solution to determining support in a browser.

Related

How to check if css value is supported by the browser?

Im not very skilled in javascript so please be bear with me. Safari 6 and below and older android mobile browsers and maybe more do not support the css value VH. My DIV#id or class is not the height of the viewport. Below is a link to a page i found some useful information, but im really not sure how to use it with a css value:
Check whether a css value is supported
Here is the code given as a shortcut for you:
if('opacity' in document.body.style) {
// do stuff
}
function isPropertySupported(property{
return property in document.body.style;
}
In the comments of the link i attached above someone does ask how to check if a css VALUE is supported and the answer is, "You set it, then read the value back and check if the browser retained it." Now im sure that would be useful information if i knew more javascript which i have just started to learn.
This is what i have in mind but im really not sure how to go around doing this.
Check if div#id or div.class has vh css value.
Check whether the css value is supported by the browser.
If its supported then keep loading. If not supported then change id or class.
So to sum up my question:
How do i check if a css value is supported by the browser using javascript or jquery?
Guidance to the answer is really appreciated.
Thanks for your help.
There is the new API CSS.supports. Supported in most browsers except IE.
console.log(
// CSS.supports(property, value)
1, CSS.supports("text-decoration-style", "blink"),
2, CSS.supports("display", "flex"),
3, CSS.supports('--foo', 'red'),
4, CSS.supports('(--foo: red)'),
// CSS.supports(DOMstring)
5, CSS.supports("( transform-origin: 5% 5% )"),
6, CSS.supports("( transform-style: preserve ) or ( -moz-transform-style: preserve ) or "
+ "( -o-transform-style: preserve ) or ( -webkit-transform-style: preserve )")
)
And there is a similar feature in CSS, the #supports feature query selector, also supported in most browsers except IE:
#supports (display: grid) {
div {
display: grid;
}
}
#supports not (display: grid) {
div {
float: right;
}
}
I assume you meant to check whether the vh value is supported, not whether specifically DIV#id bears it?
function cssPropertyValueSupported(prop, value) {
var d = document.createElement('div');
d.style[prop] = value;
return d.style[prop] === value;
}
cssPropertyValueSupported('width', '1px');
// => true
cssPropertyValueSupported('width', '1vh');
// => maybe true, maybe false (true for me)
cssPropertyValueSupported('width', '1foobar');
// => false
EDIT: This is obsolete; CSS.supports is now well supported, and should be used instead. Please support this answer instead.
We can since a while test from javascript if a css rule if available in the context with CSS.supports.
(Since Firefox 22/ Chrome 28)
console.log(
CSS.supports("( transform-origin: 5% 5% )"),
"\n",
CSS.supports("( display: flex )"),
"\n ",
CSS.supports("( background-color: #12233212 )")
)
The CSS.supports() static methods returns a Boolean value indicating
if the browser supports a given CSS feature, or not.
https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports
To go further, we can possibly use this property for browser detection.
I see the code you have there.
var styletotest = "PutStyleHere";
if (styletotest in document.body.style)
{
alert("The " + styletotest + " property is supported");
} else {
alert("The " + styletotest + " property is NOT supported");
}
Simply place the css property you want to test in the quotes where it says
PutStyleHere
And when you load the file it will show a popup telling you if it works or not.
However this seems unnecessary.
Simply Googling:
[property] css W3
where [property] is the property you want to know browser support information.
When I searched
Opacity Css W3
and then clicked on the W3 link... you can scroll down and you will see a section of the page with the info you want like this:
Source
Use the new CSS #supports feature. You can do this from CSS and also from JavaScript.
CSS:
#supports(width: 1vh) {
div#id {
width: 1vh;
}
}
/* Use at `#supports not` if you want to give an `else` condition */
#supports not (width: 1vh) {
div#id {
width: 3%;
}
}
JavaScript way:
The supports() method is provided in the CSS API to do this.
if(CSS.supports('width', '1vh')) {
document.querySelector('div#id').style.width = '1vh';
} else {
documen.querySelector('div#id').style.width = '1%';
}
Read more at CSS Conditional Rules
I'd suggest to use Modernizr.
Modernizr is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them.
Some useful links:
Modernizr: the feature detection library for HTML5/CSS3
Using Modernizr to detect HTML5 features and provide fallbacks
HTML5 Boilerplate custom build of Modernizr for feature detection
This is my code that accounts for totally unsupported properties by checking for presence of camel-Case props in the style, and uses CSS.supports if available.
const prefixes = ['', '-webkit-']
function supports(prop, value) {
if ('CSS' in window && 'supports' in window.CSS) {
for (let i = 0; i < prefixes.length; i++) {
const property = prefixes[i] + prop
if (window.CSS.supports(property, value) ) { return true }
}
return false
}
const el = document.createElement('div')
let found = false
prefixes.forEach((pr) => {
if (found) return
const p = `${pr}${prop}`
const Prop = p.replace(/-(.)/g, (m, s) => s.toUpperCase())
if (!(Prop in el.style)) return
el.style[p] = value
found = el.style[p] == value // can just check if it's not empty actually
})
return found
}
In Chromium browsers starting in version 100 you can now inspect using DevTools to see if a particular declaration (property + value) is supported.
Here is a screenshot of my website using Chrome 101 (Beta), which is the first Chromium version to support the font-palette property:
You can see in the green boxes that the #supports rule with the following conditions:
#supports (font-palette: dark) or (font-palette: light)
that in Chrome 101, both of the following declarations
font-palette: light;
font-palette: dark;
are supported.
Unlike the answers above, this is a pure DevTools -> Styles solution to determining support in a browser.

How can I detect CSS Variable support with JavaScript?

The latest version of Firefox has support for CSS Variables, but Chrome, IE and loads of other browsers do not. It should be possible to access a DOM Node or write a little method which returns whether the browser supports this feature, but I haven't been able to find anything which is currently able to do this. What I need is a solution which I can use as condition to run code if the browser does not support the feature, something like:
if (!browserCanUseCssVariables()) {
// Do stuff...
}
We can do this with CSS.supports. This is the JavaScript implementation of CSS's #supports rule which is currently available in Firefox, Chrome, Opera and Android Browser (see Can I Use...).
The CSS.supports() static methods returns a Boolean value indicating if the browser supports a given CSS feature, or not.– Mozilla Developer Network
With this, we can simply:
CSS.supports('color', 'var(--fake-var)');
The result of this will be true if the browser supports CSS variables, and false if it doesn't.
(You might think that CSS.supports('--fake-var', 0) would work, but as noted in comments on this answer Safari seems to have a bug there making it fail.)
Pure JavaScript Example
On Firefox this code snippet will produce a green background, as our CSS.supports call above returns true. In browsers which do not support CSS variables the background will be red.
var body = document.getElementsByTagName('body')[0];
if (window.CSS && CSS.supports('color', 'var(--fake-var)')) {
body.style.background = 'green';
} else {
body.style.background = 'red';
}
Note that here I've also added checks to see whether window.CSS exists - this will prevent errors being thrown in browsers which do not support this JavaScript implementation and treat that as false as well. (CSS.supports was introduced at the same time CSS global was introduced, so there's no need to check for it as well.)
Creating the browserCanUseCssVariables() function
In your case, we can create the browserCanUseCssVariables() function by simply performing the same logic. This below snippet will alert either true or false depending on the support.
function browserCanUseCssVariables() {
return window.CSS && CSS.supports('color', 'var(--fake-var)');
}
if (browserCanUseCssVariables()) {
alert('Your browser supports CSS Variables!');
} else {
alert('Your browser does not support CSS Variables and/or CSS.supports. :-(');
}
The Results (all tested on Windows only)
Firefox v31
Chrome v38
Internet Explorer 11
Set a CSS style with CSS variables and proof with Javascript and getComputedStyle() if it is set...
getComputedStyle() is supported in many browsers: http://caniuse.com/#feat=getcomputedstyle
HTML
<div class="css-variable-test"></div>
CSS
:root {
--main-bg-color: rgb(1, 2, 3); /* or something else */
}
.css-variable-test {
display: none;
background-color: var(--main-bg-color);
}
JavaScript
var computedStyle = getComputedStyle(document.getElementsByClassName('css-variable-test')[0], null);
if (computedStyle.backgroundColor == "rgb(1, 2, 3)") { // or something else
alert('CSS variables support');
}
FIDDLE: http://jsfiddle.net/g0naedLh/6/
You don’t need Javascript to detect if a browser supports custom properties, unless the Do stuff... is Javascript itself. Since the thing you’re detecting support for is CSS, I assume that the stuff you’re trying to do is all CSS. Therefore, if there’s a way to remove JS from this specific problem, I would recommend Feature Queries.
#supports (display: var(--prop)) {
h1 { font-weight: normal; }
/* all the css, even without var() */
}
Feature queries test support for syntax. You don’t have to query for display; you could use any property you want. Likewise, the value of --prop need not even exist. All you’re doing is checking to see if the browser knows how to read that syntax.
(I just chose display because almost every browser supports it. If you use flex-wrap or something, you won’t catch the browsers that do support custom props but that don’t support flexbox.)
Sidenote: I prefer calling them Custom Properties because that is exactly what they are: properties defined by the author. Yes, you can use them as variables, but there are certain advantages to them as properties, such as DOM inheritance:
body { --color-heading: green; }
article { --color-heading: blue; }
h1 { color: var(--color-heading); } /* no need for descendant selectors */
I had problems getting the window.CSS.supports method to work for testing css variables in chrome 49 (even though it has native support). Ended up doing this:
var supportsCssVars = function() {
var s = document.createElement('style'),
support;
s.innerHTML = ":root { --tmp-var: bold; }";
document.head.appendChild(s);
support = !!(window.CSS && window.CSS.supports && window.CSS.supports('font-weight', 'var(--tmp-var)'));
s.parentNode.removeChild(s);
return support;
}
console.log("Supports css variables:", supportsCssVars());
Seems to work in all browsers I tested.
Probably the code can be optimised though.

How to get opacity current value in JavaScript?

I saw some topics about already, but none have a IE10 specific solution. I know IE10 follow W3C, but I couldn't find a "official w3c solution" either for getting current opacity value of a DOM Element. Below is the code I have so far (one pice from here, another from there...):
jGp.nau.padrao is a previous setting according with browser. Will be "ie" or "w3c". As long IE10 could be "w3c" in this case, it still a useful option for other functions I have in this library. Target is a DOM Element.
jGp.ee.getAlpha = function(target){
if(jGp.nau.padrao=='w3c'){
var temp_style = document.defaultView.getComputedStyle(target,null);
if (!isNaN(temp_style.opacity)) {
opacityVal = temp_style.opacity;
} else if (!isNaN(temp_style.MozOpacity)) {
opacityVal = temp_style.MozOpacity;
} else {
opacityVal = 1; // default value so my code will not crash
}
return parseFloat(opacityVal*100);
} else {
try {
return target.filters.item('DXImageTransform.Microsoft.Alpha').Opacity;
} catch(e) {
return 100; // default value so my code will not crash
}
}
}
I can include IE versions, is previously detected too, I just need to define the right code for that. So far, this code works for FireFox, Chrome and Safari (I guess Opera too).

Is it possible to test for IE in javascript without browser sniffing and conditional comments?

I'm curious to know if it's possible to switch between Javascript insertRule and addRule methods in Javascript without using browser sniffing/conditional comments to assign addRule to IE.
In CSS, I can use properties that aren't supported on specific devices (IE ::pseudo-selector for example) to write rules for specific browsers. Is there a similar trick in Javascript?
Thanks for some insights!
if(sheet.addRule) {
sheet.addRule(...);
}
else
{
sheet.insertRule(...);
}
Use feature detection instead:
var abstractedInsertOfRule = function (rule, stylesheet){
//if (object) is a quick way to test if the object is defined
//in browsers that do not implement "insertRule",
//if (insertRule) returns "falsy"
if (insertRule) {
insertRule(rule, stylesheet);
} else if (addRule) {
addRule(rule, stylesheet);
} else {
//call other rule insertion methods here
}
};

The best way of checking for -moz-border-radius support

I wanted some of those spiffy rounded corners for a web project that I'm currently working on.
I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.
I already utilize jQuery so I looked at the excellent rounded corners plugin and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.
I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific -moz-border-radius-* properties and if so utilize them.
The check for webkit support looks like this:
var webkitAvailable = false;
try {
webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined);
}
catch(err) {}
That, however, did not work for -moz-border-radius so I started checking for alternatives.
My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.
My best solution yet is as follows.
var mozborderAvailable = false;
try {
var o = jQuery('<div>').css('-moz-border-radius', '1px');
mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px';
o = null;
} catch(err) {}
It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties
-moz-border-radius-topleft
-moz-border-radius-topright
-moz-border-radius-bottomleft
-moz-border-radius-bottomright
Is there any javascript/CSS guru out there that have a better solution?
(The feature request for this page is at http://plugins.jquery.com/node/3619)
How about this?
var mozborderAvailable = false;
try {
if (typeof(document.body.style.MozBorderRadius) !== "undefined") {
mozborderAvailable = true;
}
} catch(err) {}
I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.
(Edit: better undefined test)
I know this is an older question, but it shows up high in searches for testing border-radius support so I thought I'd throw this nugget in here.
Rob Glazebrook has a little snippet that extends the support object of jQuery to do a nice quick check for border-radius support (also moz and web-kit).
jQuery(function() {
jQuery.support.borderRadius = false;
jQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;
return (!jQuery.support.borderRadius);
}); });
Attribution
That way, if there isn't support for it you can fall back and use jQuery to implement a 2-way slider so that other browsers still have a similar visual experience.
Why not use -moz-border-radius and -webkit-border-radius in the stylesheet? It's valid CSS and throwing an otherwise unused attribute would hurt less than having javascript do the legwork of figuring out if it should apply it or not.
Then, in the javascript you'd just check if the browser is IE (or Opera?) - if it is, it'll ignore the proprietary tags, and your javascript could do it's thing.
Maybe I'm missing something here...
Apply CSS unconditionally and check element.style.MozBorderRadius in the script?
As you're already using jQuery you could use jQuery.browser utility to do some browser sniffing and then target your CSS / JavaScript accordingly.
The problem with this is that Firefox 2 does not use anti-aliasing for the borders. The script would need to detect for Firefox 3 before is uses native rounded corners as FF3 does use anti-aliasing.
I've developed the following method for detecting whether the browser supports rounded borders or not. I have yet to test it on IE (am on a Linux machine), but it works correctly in Webkit and Gecko browsers (i.e. Safari/Chrome and Firefox) as well as in Opera:
function checkBorders() {
var div = document.createElement('div');
div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
return true;
};
return false;
};
If you wanted to test for Firefox 2 or 3, you should check for the Gecko rendering engine, not the actual browser. I can't find the precise release date for Gecko 1.9 (which is the version that supports anti-aliased rounded corners), but the Mozilla wiki says it was released in the first quarter of 2007, so we'll assume May just to be sure.
if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 )
All in all, the combined function is this:
function checkBorders() {
if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 ) {
return true;
} else {
var div = document.createElement('div');
div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
return true;
};
return false;
};
};

Categories

Resources