Detect CSS transitions using Javascript (and without modernizr)? - javascript

How would I detect that a browser supports CSS transitions using Javascript (and without using modernizr)?

Perhaps something like this. Basically it's just looking to see if the CSS transition property has been defined:
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if (typeof s[p] == 'string') { return true; }
// Tests for vendor specific prop
var v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];
p = p.charAt(0).toUpperCase() + p.substr(1);
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
Adapted from this gist. All credit goes there.

3 ways of doing so:
var supportsTransitions = (function() {
var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
v = ['ms','O','Moz','Webkit']; // 'v' for vendor
if( s['transition'] == '' ) return true; // check first for prefeixed-free support
while( v.length ) // now go over the list of vendor prefixes and check support until one is found
if( v.pop() + 'Transition' in s )
return true;
return false;
})();
console.log(supportsTransitions) // 'true' on modern browsers
OR:
var s = document.createElement('p').style,
supportsTransitions = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
console.log(supportsTransitions); // 'true' on modren browsers
If you actually want to use the right prefixed, use this:
function getPrefixed(prop){
var i, s = document.createElement('p').style, v = ['ms','O','Moz','Webkit'];
if( s[prop] == '' ) return prop;
prop = prop.charAt(0).toUpperCase() + prop.slice(1);
for( i = v.length; i--; )
if( s[v[i] + prop] == '' )
return (v[i] + prop);
}
// get the correct vendor prefixed property
transition = getPrefixed('transition');
// usage example
elment.style[transition] = '1s';

As of 2015, this one-liner should do the deal (IE 10+, Chrome 1+, Safari 3.2+, FF 4+ and Opera 12+):-
var transitionsSupported = ('transition' in document.documentElement.style) || ('WebkitTransition' in document.documentElement.style);

Here the way I used:
var style = document.documentElement.style;
if (
style.webkitTransition !== undefined ||
style.MozTransition !== undefined ||
style.OTransition !== undefined ||
style.MsTransition !== undefined ||
style.transition !== undefined
)
{
// Support CSS3 transititon
}

Also you can use the following approach (kind of one line function):
var features;
(function(s, features) {
features.transitions = 'transition' in s || 'webkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
})(document.createElement('div').style, features || (features = {}));
console.log(features.transitions);

Related

bootstrap-select is flashbacked,i used django and bootstrap [duplicate]

I have some JavaScript code that gives this error:
Uncaught TypeError: Cannot read property 'value' of undefined
Here is my code:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
What does this error mean?
Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.
Try this, It always works, and you will get NO TypeError:
try{
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}catch(e){
if(e){
// If fails, Do something else
}
}
First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like
if (typeof document.getElementsByName("username")[0] != 'undefined')
Similarly for the other element password.
The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.
You can just create a function to check if the variable exists, else will return a default value :
function isSet(element, defaultVal){
if(typeof element != 'undefined'){
return element;
}
console.log('one missing element');
return defaultVal;
}
And use it in a variable check:
var variable = isSet(variable, 'Default value');
You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

How to fix isInteger for Internet Explorer [duplicate]

i have this error in internet explorer console ' Object doesn't support property or method 'isInteger' ' how can i resolve it ?
code:
function verificaNota(nota){
if (nota.length>0){
var arr = [];
if( nota.indexOf(".") != -1 ){
return ferificareArrayNote(nota.split('.'));
}else if( nota.indexOf(",") != -1 ){
ferificareArrayNote(nota.split(','));
}else if( nota.length<=2 && Number.isInteger(Number(nota)) && Number(nota)<=10 && Number(nota) > 0){
return true;
}else {
return false;
}
}
return true;
}
And yes, i pass it a number not char;
As stated by #Andreas, Number.isNumber is part of ES6 so not supported by IE11
You can add the following polyfill to you javasript
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

Internet Explorer 11 : Object doesn't support property or method 'isInteger'

i have this error in internet explorer console ' Object doesn't support property or method 'isInteger' ' how can i resolve it ?
code:
function verificaNota(nota){
if (nota.length>0){
var arr = [];
if( nota.indexOf(".") != -1 ){
return ferificareArrayNote(nota.split('.'));
}else if( nota.indexOf(",") != -1 ){
ferificareArrayNote(nota.split(','));
}else if( nota.length<=2 && Number.isInteger(Number(nota)) && Number(nota)<=10 && Number(nota) > 0){
return true;
}else {
return false;
}
}
return true;
}
And yes, i pass it a number not char;
As stated by #Andreas, Number.isNumber is part of ES6 so not supported by IE11
You can add the following polyfill to you javasript
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

Detect Safari using jQuery

Though both are Webkit based browsers, Safari urlencodes quotation marks in the URL while Chrome does not.
Therefore I need to distinguish between these two in JS.
jQuery's browser detection docs mark "safari" as deprecated.
Is there a better method or do I just stick with the deprecated value for now?
Using a mix of feature detection and Useragent string:
var is_opera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var is_Edge = navigator.userAgent.indexOf("Edge") > -1;
var is_chrome = !!window.chrome && !is_opera && !is_Edge;
var is_explorer= typeof document !== 'undefined' && !!document.documentMode && !is_Edge;
var is_firefox = typeof window.InstallTrigger !== 'undefined';
var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
Usage:
if (is_safari) alert('Safari');
Or for Safari only, use this :
if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}
The following identifies Safari 3.0+ and distinguishes it from Chrome:
isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)
unfortunately the above examples will also detect android's default browser as Safari, which it is not.
I used
navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1
For checking Safari I used this:
$.browser.safari = ($.browser.webkit && !(/chrome/.test(navigator.userAgent.toLowerCase())));
if ($.browser.safari) {
alert('this is safari');
}
It works correctly.
Apparently the only reliable and accepted solution would be to do feature detection like this:
browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
The only way I found is check if navigator.userAgent contains iPhone or iPad word
if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
//is safari
}
If you are checking the browser use $.browser. But if you are checking feature support (recommended) then use $.support.
You should NOT use $.browser to enable/disable features on the page. Reason being its not dependable and generally just not recommended.
If you need feature support then I recommend modernizr.
//Check if Safari
function isSafari() {
return /^((?!chrome).)*safari/i.test(navigator.userAgent);
}
//Check if MAC
if(navigator.userAgent.indexOf('Mac')>1){
alert(isSafari());
}
http://jsfiddle.net/s1o943gb/10/
This will determine whether the browser is Safari or not.
if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
alert(its safari);
}else {
alert('its not safari');
}
I use to detect Apple browser engine, this simple JavaScript condition:
navigator.vendor.startsWith('Apple')
A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.
Using jQuery it goes like this:
"use strict";
$(document).ready(function() {
var appVersion = navigator.appVersion;
var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;
var webkitVersion_positionEnd = webkitVersion_positionStart + 3;
var webkitVersion = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);
console.log(webkitVersion);
if (webkitVersion < 537) {
console.log("webkit outdated.");
} else {
console.log("webkit ok.");
};
});
This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.
Happy coding!
// Safari uses pre-calculated pixels, so use this feature to detect Safari
var canva = document.createElement('canvas');
var ctx = canva.getContext("2d");
var img = ctx.getImageData(0, 0, 1, 1);
var pix = img.data; // byte array, rgba
var isSafari = (pix[3] != 0); // alpha in Safari is not zero
Generic FUNCTION
var getBrowseActive = function (browserName) {
return navigator.userAgent.indexOf(browserName) > -1;
};
My best solution
function getBrowserInfo() {
const ua = navigator.userAgent; let tem;
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'IE ', version: (tem[1] || '') };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\bOPR\/(\d+)/);
if (tem != null) {
return { name: 'Opera', version: tem[1] };
}
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
tem = ua.match(/version\/(\d+)/i);
if (tem != null) {
M.splice(1, 1, tem[1]);
}
return {
name: M[0],
version: M[1],
};
}
getBrowserInfo();

Javascript error in jssh in Firefox 4.0b1

Using this Javascript through jssh compiled and built for the new Firefox 4.0 beta 1 returns an odd message. Here is the code (sorry if it's a little messy).
In summary the code checks all frames of a Firefox window which is a test page of our unit tests for a <td> element that has an onclick which contains the phrase Goodbye Wonderful, instead of getting a failed response back we are receiving this odd nserror at the end which we cannot explain.
var firefoxWindow = getWindows()[0];
var browser = firefoxWindow.getBrowser();
var doc = browser.contentDocument;
var elem = null;
var elems = doc.getElementsByTagName('td');
for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/doNothing/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } }
var found = false;
var window = null;
for(var i=0; i < firefoxWindow.frames.length; i++){if(firefoxWindow.frames[i].toString().toLowerCase().indexOf('object window') > -1){window = firefoxWindow.frames[i]; break;}}
function recursiveSearch(frames){ for(var i=0; i<frames.length; i++){var elems = frames[i].document.getElementsByTagName('td'); for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } } if(elem){found = true; return;} else{ if(frames[i].frames.length>0){recursiveSearch(frames[i].frames);}}}}if(!elem && window.frames.length > 0){ recursiveSearch(window.frames); }var origColor = '';if(elem !== null){origColor = elem.style.backgroundColor;if(origColor === null){origColor = '';} elem.style.backgroundColor = 'yellow';}
Here is the return message from jssh :
Received: uncaught exception: [Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: interactive :: <TOP_LEVEL> :: line 1" data: no]
JSSh is no longer supported in Firefox 4 and is a mess to handle, switching to mozrepl since it's written mostly in javascript and adding my own javascript commands directly to the extension seems to be a better way of accomplishing certain things.

Categories

Resources