PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/packages/Modernizr.1.7/Content/Scripts/modernizr-1.7.js

#
JavaScript | 969 lines | 602 code | 137 blank | 230 comment | 42 complexity | 43e8e02f16dfced26e98b88a05acea52 MD5 | raw file
  1. /*!
  2. * Note: While Microsoft is not the author of this file, Microsoft is
  3. * offering you a license subject to the terms of the Microsoft Software
  4. * License Terms for Microsoft ASP.NET Model View Controller 3.
  5. * Microsoft reserves all other rights. The notices below are provided
  6. * for informational purposes only and are not the license terms under
  7. * which Microsoft distributed this file.
  8. *
  9. * Modernizr v1.7
  10. * http://www.modernizr.com
  11. *
  12. * Developed by:
  13. * - Faruk Ates http://farukat.es/
  14. * - Paul Irish http://paulirish.com/
  15. *
  16. * Copyright (c) 2009-2011
  17. */
  18. /*
  19. * Modernizr is a script that detects native CSS3 and HTML5 features
  20. * available in the current UA and provides an object containing all
  21. * features with a true/false value, depending on whether the UA has
  22. * native support for it or not.
  23. *
  24. * Modernizr will also add classes to the <html> element of the page,
  25. * one for each feature it detects. If the UA supports it, a class
  26. * like "cssgradients" will be added. If not, the class name will be
  27. * "no-cssgradients". This allows for simple if-conditionals in your
  28. * CSS, giving you fine control over the look & feel of your website.
  29. *
  30. * @author Faruk Ates
  31. * @author Paul Irish
  32. * @copyright (c) 2009-2011 Faruk Ates.
  33. * @contributor Ben Alman
  34. */
  35. window.Modernizr = (function(window,document,undefined){
  36. var version = '1.7',
  37. ret = {},
  38. /**
  39. * !! DEPRECATED !!
  40. *
  41. * enableHTML5 is a private property for advanced use only. If enabled,
  42. * it will make Modernizr.init() run through a brief while() loop in
  43. * which it will create all HTML5 elements in the DOM to allow for
  44. * styling them in Internet Explorer, which does not recognize any
  45. * non-HTML4 elements unless created in the DOM this way.
  46. *
  47. * enableHTML5 is ON by default.
  48. *
  49. * The enableHTML5 toggle option is DEPRECATED as per 1.6, and will be
  50. * replaced in 2.0 in lieu of the modular, configurable nature of 2.0.
  51. */
  52. enableHTML5 = true,
  53. docElement = document.documentElement,
  54. docHead = document.head || document.getElementsByTagName('head')[0],
  55. /**
  56. * Create our "modernizr" element that we do most feature tests on.
  57. */
  58. mod = 'modernizr',
  59. modElem = document.createElement( mod ),
  60. m_style = modElem.style,
  61. /**
  62. * Create the input element for various Web Forms feature tests.
  63. */
  64. inputElem = document.createElement( 'input' ),
  65. smile = ':)',
  66. tostring = Object.prototype.toString,
  67. // List of property values to set for css tests. See ticket #21
  68. prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
  69. // Following spec is to expose vendor-specific style properties as:
  70. // elem.style.WebkitBorderRadius
  71. // and the following would be incorrect:
  72. // elem.style.webkitBorderRadius
  73. // Webkit ghosts their properties in lowercase but Opera & Moz do not.
  74. // Microsoft foregoes prefixes entirely <= IE8, but appears to
  75. // use a lowercase `ms` instead of the correct `Ms` in IE9
  76. // More here: http://github.com/Modernizr/Modernizr/issues/issue/21
  77. domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
  78. ns = {'svg': 'http://www.w3.org/2000/svg'},
  79. tests = {},
  80. inputs = {},
  81. attrs = {},
  82. classes = [],
  83. featurename, // used in testing loop
  84. // todo: consider using http://javascript.nwbox.com/CSSSupport/css-support.js instead
  85. testMediaQuery = function(mq){
  86. var st = document.createElement('style'),
  87. div = document.createElement('div'),
  88. ret;
  89. st.textContent = mq + '{#modernizr{height:3px}}';
  90. docHead.appendChild(st);
  91. div.id = 'modernizr';
  92. docElement.appendChild(div);
  93. ret = div.offsetHeight === 3;
  94. st.parentNode.removeChild(st);
  95. div.parentNode.removeChild(div);
  96. return !!ret;
  97. },
  98. /**
  99. * isEventSupported determines if a given element supports the given event
  100. * function from http://yura.thinkweb2.com/isEventSupported/
  101. */
  102. isEventSupported = (function(){
  103. var TAGNAMES = {
  104. 'select':'input','change':'input',
  105. 'submit':'form','reset':'form',
  106. 'error':'img','load':'img','abort':'img'
  107. };
  108. function isEventSupported(eventName, element) {
  109. element = element || document.createElement(TAGNAMES[eventName] || 'div');
  110. eventName = 'on' + eventName;
  111. // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
  112. var isSupported = (eventName in element);
  113. if (!isSupported) {
  114. // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
  115. if (!element.setAttribute) {
  116. element = document.createElement('div');
  117. }
  118. if (element.setAttribute && element.removeAttribute) {
  119. element.setAttribute(eventName, '');
  120. isSupported = is(element[eventName], 'function');
  121. // If property was created, "remove it" (by setting value to `undefined`)
  122. if (!is(element[eventName], undefined)) {
  123. element[eventName] = undefined;
  124. }
  125. element.removeAttribute(eventName);
  126. }
  127. }
  128. element = null;
  129. return isSupported;
  130. }
  131. return isEventSupported;
  132. })();
  133. // hasOwnProperty shim by kangax needed for Safari 2.0 support
  134. var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty;
  135. if (!is(_hasOwnProperty, undefined) && !is(_hasOwnProperty.call, undefined)) {
  136. hasOwnProperty = function (object, property) {
  137. return _hasOwnProperty.call(object, property);
  138. };
  139. }
  140. else {
  141. hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
  142. return ((property in object) && is(object.constructor.prototype[property], undefined));
  143. };
  144. }
  145. /**
  146. * set_css applies given styles to the Modernizr DOM node.
  147. */
  148. function set_css( str ) {
  149. m_style.cssText = str;
  150. }
  151. /**
  152. * set_css_all extrapolates all vendor-specific css strings.
  153. */
  154. function set_css_all( str1, str2 ) {
  155. return set_css(prefixes.join(str1 + ';') + ( str2 || '' ));
  156. }
  157. /**
  158. * is returns a boolean for if typeof obj is exactly type.
  159. */
  160. function is( obj, type ) {
  161. return typeof obj === type;
  162. }
  163. /**
  164. * contains returns a boolean for if substr is found within str.
  165. */
  166. function contains( str, substr ) {
  167. return (''+str).indexOf( substr ) !== -1;
  168. }
  169. /**
  170. * test_props is a generic CSS / DOM property test; if a browser supports
  171. * a certain property, it won't return undefined for it.
  172. * A supported CSS property returns empty string when its not yet set.
  173. */
  174. function test_props( props, callback ) {
  175. for ( var i in props ) {
  176. if ( m_style[ props[i] ] !== undefined && ( !callback || callback( props[i], modElem ) ) ) {
  177. return true;
  178. }
  179. }
  180. }
  181. /**
  182. * test_props_all tests a list of DOM properties we want to check against.
  183. * We specify literally ALL possible (known and/or likely) properties on
  184. * the element including the non-vendor prefixed one, for forward-
  185. * compatibility.
  186. */
  187. function test_props_all( prop, callback ) {
  188. var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),
  189. props = (prop + ' ' + domPrefixes.join(uc_prop + ' ') + uc_prop).split(' ');
  190. return !!test_props( props, callback );
  191. }
  192. /**
  193. * Tests
  194. * -----
  195. */
  196. tests['flexbox'] = function() {
  197. /**
  198. * set_prefixed_value_css sets the property of a specified element
  199. * adding vendor prefixes to the VALUE of the property.
  200. * @param {Element} element
  201. * @param {string} property The property name. This will not be prefixed.
  202. * @param {string} value The value of the property. This WILL be prefixed.
  203. * @param {string=} extra Additional CSS to append unmodified to the end of
  204. * the CSS string.
  205. */
  206. function set_prefixed_value_css(element, property, value, extra) {
  207. property += ':';
  208. element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || '');
  209. }
  210. /**
  211. * set_prefixed_property_css sets the property of a specified element
  212. * adding vendor prefixes to the NAME of the property.
  213. * @param {Element} element
  214. * @param {string} property The property name. This WILL be prefixed.
  215. * @param {string} value The value of the property. This will not be prefixed.
  216. * @param {string=} extra Additional CSS to append unmodified to the end of
  217. * the CSS string.
  218. */
  219. function set_prefixed_property_css(element, property, value, extra) {
  220. element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || '');
  221. }
  222. var c = document.createElement('div'),
  223. elem = document.createElement('div');
  224. set_prefixed_value_css(c, 'display', 'box', 'width:42px;padding:0;');
  225. set_prefixed_property_css(elem, 'box-flex', '1', 'width:10px;');
  226. c.appendChild(elem);
  227. docElement.appendChild(c);
  228. var ret = elem.offsetWidth === 42;
  229. c.removeChild(elem);
  230. docElement.removeChild(c);
  231. return ret;
  232. };
  233. // On the S60 and BB Storm, getContext exists, but always returns undefined
  234. // http://github.com/Modernizr/Modernizr/issues/issue/97/
  235. tests['canvas'] = function() {
  236. var elem = document.createElement( 'canvas' );
  237. return !!(elem.getContext && elem.getContext('2d'));
  238. };
  239. tests['canvastext'] = function() {
  240. return !!(ret['canvas'] && is(document.createElement( 'canvas' ).getContext('2d').fillText, 'function'));
  241. };
  242. // This WebGL test false positives in FF depending on graphics hardware. But really it's quite impossible to know
  243. // wether webgl will succeed until after you create the context. You might have hardware that can support
  244. // a 100x100 webgl canvas, but will not support a 1000x1000 webgl canvas. So this feature inference is weak,
  245. // but intentionally so.
  246. tests['webgl'] = function(){
  247. return !!window.WebGLRenderingContext;
  248. };
  249. /*
  250. * The Modernizr.touch test only indicates if the browser supports
  251. * touch events, which does not necessarily reflect a touchscreen
  252. * device, as evidenced by tablets running Windows 7 or, alas,
  253. * the Palm Pre / WebOS (touch) phones.
  254. *
  255. * Additionally, Chrome (desktop) used to lie about its support on this,
  256. * but that has since been rectified: http://crbug.com/36415
  257. *
  258. * We also test for Firefox 4 Multitouch Support.
  259. *
  260. * For more info, see: http://modernizr.github.com/Modernizr/touch.html
  261. */
  262. tests['touch'] = function() {
  263. return ('ontouchstart' in window) || testMediaQuery('@media ('+prefixes.join('touch-enabled),(')+'modernizr)');
  264. };
  265. /**
  266. * geolocation tests for the new Geolocation API specification.
  267. * This test is a standards compliant-only test; for more complete
  268. * testing, including a Google Gears fallback, please see:
  269. * http://code.google.com/p/geo-location-javascript/
  270. * or view a fallback solution using google's geo API:
  271. * http://gist.github.com/366184
  272. */
  273. tests['geolocation'] = function() {
  274. return !!navigator.geolocation;
  275. };
  276. // Per 1.6:
  277. // This used to be Modernizr.crosswindowmessaging but the longer
  278. // name has been deprecated in favor of a shorter and property-matching one.
  279. // The old API is still available in 1.6, but as of 2.0 will throw a warning,
  280. // and in the first release thereafter disappear entirely.
  281. tests['postmessage'] = function() {
  282. return !!window.postMessage;
  283. };
  284. // Web SQL database detection is tricky:
  285. // In chrome incognito mode, openDatabase is truthy, but using it will
  286. // throw an exception: http://crbug.com/42380
  287. // We can create a dummy database, but there is no way to delete it afterwards.
  288. // Meanwhile, Safari users can get prompted on any database creation.
  289. // If they do, any page with Modernizr will give them a prompt:
  290. // http://github.com/Modernizr/Modernizr/issues/closed#issue/113
  291. // We have chosen to allow the Chrome incognito false positive, so that Modernizr
  292. // doesn't litter the web with these test databases. As a developer, you'll have
  293. // to account for this gotcha yourself.
  294. tests['websqldatabase'] = function() {
  295. var result = !!window.openDatabase;
  296. /* if (result){
  297. try {
  298. result = !!openDatabase( mod + "testdb", "1.0", mod + "testdb", 2e4);
  299. } catch(e) {
  300. }
  301. } */
  302. return result;
  303. };
  304. // Vendors have inconsistent prefixing with the experimental Indexed DB:
  305. // - Firefox is shipping indexedDB in FF4 as moz_indexedDB
  306. // - Webkit's implementation is accessible through webkitIndexedDB
  307. // We test both styles.
  308. tests['indexedDB'] = function(){
  309. for (var i = -1, len = domPrefixes.length; ++i < len; ){
  310. var prefix = domPrefixes[i].toLowerCase();
  311. if (window[prefix + '_indexedDB'] || window[prefix + 'IndexedDB']){
  312. return true;
  313. }
  314. }
  315. return false;
  316. };
  317. // documentMode logic from YUI to filter out IE8 Compat Mode
  318. // which false positives.
  319. tests['hashchange'] = function() {
  320. return isEventSupported('hashchange', window) && ( document.documentMode === undefined || document.documentMode > 7 );
  321. };
  322. // Per 1.6:
  323. // This used to be Modernizr.historymanagement but the longer
  324. // name has been deprecated in favor of a shorter and property-matching one.
  325. // The old API is still available in 1.6, but as of 2.0 will throw a warning,
  326. // and in the first release thereafter disappear entirely.
  327. tests['history'] = function() {
  328. return !!(window.history && history.pushState);
  329. };
  330. tests['draganddrop'] = function() {
  331. return isEventSupported('dragstart') && isEventSupported('drop');
  332. };
  333. tests['websockets'] = function(){
  334. return ('WebSocket' in window);
  335. };
  336. // http://css-tricks.com/rgba-browser-support/
  337. tests['rgba'] = function() {
  338. // Set an rgba() color and check the returned value
  339. set_css( 'background-color:rgba(150,255,150,.5)' );
  340. return contains( m_style.backgroundColor, 'rgba' );
  341. };
  342. tests['hsla'] = function() {
  343. // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
  344. // except IE9 who retains it as hsla
  345. set_css('background-color:hsla(120,40%,100%,.5)' );
  346. return contains( m_style.backgroundColor, 'rgba' ) || contains( m_style.backgroundColor, 'hsla' );
  347. };
  348. tests['multiplebgs'] = function() {
  349. // Setting multiple images AND a color on the background shorthand property
  350. // and then querying the style.background property value for the number of
  351. // occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
  352. set_css( 'background:url(//:),url(//:),red url(//:)' );
  353. // If the UA supports multiple backgrounds, there should be three occurrences
  354. // of the string "url(" in the return value for elem_style.background
  355. return new RegExp("(url\\s*\\(.*?){3}").test(m_style.background);
  356. };
  357. // In testing support for a given CSS property, it's legit to test:
  358. // `elem.style[styleName] !== undefined`
  359. // If the property is supported it will return an empty string,
  360. // if unsupported it will return undefined.
  361. // We'll take advantage of this quick test and skip setting a style
  362. // on our modernizr element, but instead just testing undefined vs
  363. // empty string.
  364. tests['backgroundsize'] = function() {
  365. return test_props_all( 'backgroundSize' );
  366. };
  367. tests['borderimage'] = function() {
  368. return test_props_all( 'borderImage' );
  369. };
  370. // Super comprehensive table about all the unique implementations of
  371. // border-radius: http://muddledramblings.com/table-of-css3-border-radius-compliance
  372. tests['borderradius'] = function() {
  373. return test_props_all( 'borderRadius', '', function( prop ) {
  374. return contains( prop, 'orderRadius' );
  375. });
  376. };
  377. // WebOS unfortunately false positives on this test.
  378. tests['boxshadow'] = function() {
  379. return test_props_all( 'boxShadow' );
  380. };
  381. // FF3.0 will false positive on this test
  382. tests['textshadow'] = function(){
  383. return document.createElement('div').style.textShadow === '';
  384. };
  385. tests['opacity'] = function() {
  386. // Browsers that actually have CSS Opacity implemented have done so
  387. // according to spec, which means their return values are within the
  388. // range of [0.0,1.0] - including the leading zero.
  389. set_css_all( 'opacity:.55' );
  390. // The non-literal . in this regex is intentional:
  391. // German Chrome returns this value as 0,55
  392. // https://github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
  393. return /^0.55$/.test(m_style.opacity);
  394. };
  395. tests['cssanimations'] = function() {
  396. return test_props_all( 'animationName' );
  397. };
  398. tests['csscolumns'] = function() {
  399. return test_props_all( 'columnCount' );
  400. };
  401. tests['cssgradients'] = function() {
  402. /**
  403. * For CSS Gradients syntax, please see:
  404. * http://webkit.org/blog/175/introducing-css-gradients/
  405. * https://developer.mozilla.org/en/CSS/-moz-linear-gradient
  406. * https://developer.mozilla.org/en/CSS/-moz-radial-gradient
  407. * http://dev.w3.org/csswg/css3-images/#gradients-
  408. */
  409. var str1 = 'background-image:',
  410. str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
  411. str3 = 'linear-gradient(left top,#9f9, white);';
  412. set_css(
  413. (str1 + prefixes.join(str2 + str1) + prefixes.join(str3 + str1)).slice(0,-str1.length)
  414. );
  415. return contains( m_style.backgroundImage, 'gradient' );
  416. };
  417. tests['cssreflections'] = function() {
  418. return test_props_all( 'boxReflect' );
  419. };
  420. tests['csstransforms'] = function() {
  421. return !!test_props([ 'transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ]);
  422. };
  423. tests['csstransforms3d'] = function() {
  424. var ret = !!test_props([ 'perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective' ]);
  425. // Webkitâ&#x20AC;&#x2122;s 3D transforms are passed off to the browser's own graphics renderer.
  426. // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
  427. // some conditions. As a result, Webkit typically recognizes the syntax but
  428. // will sometimes throw a false positive, thus we must do a more thorough check:
  429. if (ret && 'webkitPerspective' in docElement.style){
  430. // Webkit allows this media query to succeed only if the feature is enabled.
  431. // `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }`
  432. ret = testMediaQuery('@media ('+prefixes.join('transform-3d),(')+'modernizr)');
  433. }
  434. return ret;
  435. };
  436. tests['csstransitions'] = function() {
  437. return test_props_all( 'transitionProperty' );
  438. };
  439. // @font-face detection routine by Diego Perini
  440. // http://javascript.nwbox.com/CSSSupport/
  441. tests['fontface'] = function(){
  442. var
  443. sheet, bool,
  444. head = docHead || docElement,
  445. style = document.createElement("style"),
  446. impl = document.implementation || { hasFeature: function() { return false; } };
  447. style.type = 'text/css';
  448. head.insertBefore(style, head.firstChild);
  449. sheet = style.sheet || style.styleSheet;
  450. var supportAtRule = impl.hasFeature('CSS2', '') ?
  451. function(rule) {
  452. if (!(sheet && rule)) return false;
  453. var result = false;
  454. try {
  455. sheet.insertRule(rule, 0);
  456. result = (/src/i).test(sheet.cssRules[0].cssText);
  457. sheet.deleteRule(sheet.cssRules.length - 1);
  458. } catch(e) { }
  459. return result;
  460. } :
  461. function(rule) {
  462. if (!(sheet && rule)) return false;
  463. sheet.cssText = rule;
  464. return sheet.cssText.length !== 0 && (/src/i).test(sheet.cssText) &&
  465. sheet.cssText
  466. .replace(/\r+|\n+/g, '')
  467. .indexOf(rule.split(' ')[0]) === 0;
  468. };
  469. bool = supportAtRule('@font-face { font-family: "font"; src: url(data:,); }');
  470. head.removeChild(style);
  471. return bool;
  472. };
  473. // These tests evaluate support of the video/audio elements, as well as
  474. // testing what types of content they support.
  475. //
  476. // We're using the Boolean constructor here, so that we can extend the value
  477. // e.g. Modernizr.video // true
  478. // Modernizr.video.ogg // 'probably'
  479. //
  480. // Codec values from : http://github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
  481. // thx to NielsLeenheer and zcorpan
  482. // Note: in FF 3.5.1 and 3.5.0, "no" was a return value instead of empty string.
  483. // Modernizr does not normalize for that.
  484. tests['video'] = function() {
  485. var elem = document.createElement('video'),
  486. bool = !!elem.canPlayType;
  487. if (bool){
  488. bool = new Boolean(bool);
  489. bool.ogg = elem.canPlayType('video/ogg; codecs="theora"');
  490. // Workaround required for IE9, which doesn't report video support without audio codec specified.
  491. // bug 599718 @ msft connect
  492. var h264 = 'video/mp4; codecs="avc1.42E01E';
  493. bool.h264 = elem.canPlayType(h264 + '"') || elem.canPlayType(h264 + ', mp4a.40.2"');
  494. bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"');
  495. }
  496. return bool;
  497. };
  498. tests['audio'] = function() {
  499. var elem = document.createElement('audio'),
  500. bool = !!elem.canPlayType;
  501. if (bool){
  502. bool = new Boolean(bool);
  503. bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
  504. bool.mp3 = elem.canPlayType('audio/mpeg;');
  505. // Mimetypes accepted:
  506. // https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  507. // http://bit.ly/iphoneoscodecs
  508. bool.wav = elem.canPlayType('audio/wav; codecs="1"');
  509. bool.m4a = elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;');
  510. }
  511. return bool;
  512. };
  513. // Firefox has made these tests rather unfun.
  514. // In FF4, if disabled, window.localStorage should === null.
  515. // Normally, we could not test that directly and need to do a
  516. // `('localStorage' in window) && ` test first because otherwise Firefox will
  517. // throw http://bugzil.la/365772 if cookies are disabled
  518. // However, in Firefox 4 betas, if dom.storage.enabled == false, just mentioning
  519. // the property will throw an exception. http://bugzil.la/599479
  520. // This looks to be fixed for FF4 Final.
  521. // Because we are forced to try/catch this, we'll go aggressive.
  522. // FWIW: IE8 Compat mode supports these features completely:
  523. // http://www.quirksmode.org/dom/html5.html
  524. // But IE8 doesn't support either with local files
  525. tests['localstorage'] = function() {
  526. try {
  527. return !!localStorage.getItem;
  528. } catch(e) {
  529. return false;
  530. }
  531. };
  532. tests['sessionstorage'] = function() {
  533. try {
  534. return !!sessionStorage.getItem;
  535. } catch(e){
  536. return false;
  537. }
  538. };
  539. tests['webWorkers'] = function () {
  540. return !!window.Worker;
  541. };
  542. tests['applicationcache'] = function() {
  543. return !!window.applicationCache;
  544. };
  545. // Thanks to Erik Dahlstrom
  546. tests['svg'] = function(){
  547. return !!document.createElementNS && !!document.createElementNS(ns.svg, "svg").createSVGRect;
  548. };
  549. tests['inlinesvg'] = function() {
  550. var div = document.createElement('div');
  551. div.innerHTML = '<svg/>';
  552. return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
  553. };
  554. // Thanks to F1lt3r and lucideer
  555. // http://github.com/Modernizr/Modernizr/issues#issue/35
  556. tests['smil'] = function(){
  557. return !!document.createElementNS && /SVG/.test(tostring.call(document.createElementNS(ns.svg,'animate')));
  558. };
  559. tests['svgclippaths'] = function(){
  560. // Possibly returns a false positive in Safari 3.2?
  561. return !!document.createElementNS && /SVG/.test(tostring.call(document.createElementNS(ns.svg,'clipPath')));
  562. };
  563. // input features and input types go directly onto the ret object, bypassing the tests loop.
  564. // Hold this guy to execute in a moment.
  565. function webforms(){
  566. // Run through HTML5's new input attributes to see if the UA understands any.
  567. // We're using f which is the <input> element created early on
  568. // Mike Taylr has created a comprehensive resource for testing these attributes
  569. // when applied to all input types:
  570. // http://miketaylr.com/code/input-type-attr.html
  571. // spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
  572. ret['input'] = (function(props) {
  573. for (var i = 0, len = props.length; i<len; i++) {
  574. attrs[ props[i] ] = !!(props[i] in inputElem);
  575. }
  576. return attrs;
  577. })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
  578. // Run through HTML5's new input types to see if the UA understands any.
  579. // This is put behind the tests runloop because it doesn't return a
  580. // true/false like all the other tests; instead, it returns an object
  581. // containing each input type with its corresponding true/false value
  582. // Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/
  583. ret['inputtypes'] = (function(props) {
  584. for (var i = 0, bool, inputElemType, defaultView, len=props.length; i < len; i++) {
  585. inputElem.setAttribute('type', inputElemType = props[i]);
  586. bool = inputElem.type !== 'text';
  587. // We first check to see if the type we give it sticks..
  588. // If the type does, we feed it a textual value, which shouldn't be valid.
  589. // If the value doesn't stick, we know there's input sanitization which infers a custom UI
  590. if (bool){
  591. inputElem.value = smile;
  592. inputElem.style.cssText = 'position:absolute;visibility:hidden;';
  593. if (/^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined){
  594. docElement.appendChild(inputElem);
  595. defaultView = document.defaultView;
  596. // Safari 2-4 allows the smiley as a value, despite making a slider
  597. bool = defaultView.getComputedStyle &&
  598. defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
  599. // Mobile android web browser has false positive, so must
  600. // check the height to see if the widget is actually there.
  601. (inputElem.offsetHeight !== 0);
  602. docElement.removeChild(inputElem);
  603. } else if (/^(search|tel)$/.test(inputElemType)){
  604. // Spec doesnt define any special parsing or detectable UI
  605. // behaviors so we pass these through as true
  606. // Interestingly, opera fails the earlier test, so it doesn't
  607. // even make it here.
  608. } else if (/^(url|email)$/.test(inputElemType)) {
  609. // Real url and email support comes with prebaked validation.
  610. bool = inputElem.checkValidity && inputElem.checkValidity() === false;
  611. } else if (/^color$/.test(inputElemType)) {
  612. // chuck into DOM and force reflow for Opera bug in 11.00
  613. // github.com/Modernizr/Modernizr/issues#issue/159
  614. docElement.appendChild(inputElem);
  615. docElement.offsetWidth;
  616. bool = inputElem.value != smile;
  617. docElement.removeChild(inputElem);
  618. } else {
  619. // If the upgraded input compontent rejects the :) text, we got a winner
  620. bool = inputElem.value != smile;
  621. }
  622. }
  623. inputs[ props[i] ] = !!bool;
  624. }
  625. return inputs;
  626. })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
  627. }
  628. // End of test definitions
  629. // -----------------------
  630. // Run through all tests and detect their support in the current UA.
  631. // todo: hypothetically we could be doing an array of tests and use a basic loop here.
  632. for ( var feature in tests ) {
  633. if ( hasOwnProperty( tests, feature ) ) {
  634. // run the test, throw the return value into the Modernizr,
  635. // then based on that boolean, define an appropriate className
  636. // and push it into an array of classes we'll join later.
  637. featurename = feature.toLowerCase();
  638. ret[ featurename ] = tests[ feature ]();
  639. classes.push( ( ret[ featurename ] ? '' : 'no-' ) + featurename );
  640. }
  641. }
  642. // input tests need to run.
  643. if (!ret.input) webforms();
  644. // Per 1.6: deprecated API is still accesible for now:
  645. ret.crosswindowmessaging = ret.postmessage;
  646. ret.historymanagement = ret.history;
  647. /**
  648. * Addtest allows the user to define their own feature tests
  649. * the result will be added onto the Modernizr object,
  650. * as well as an appropriate className set on the html element
  651. *
  652. * @param feature - String naming the feature
  653. * @param test - Function returning true if feature is supported, false if not
  654. */
  655. ret.addTest = function (feature, test) {
  656. feature = feature.toLowerCase();
  657. if (ret[ feature ]) {
  658. return; // quit if you're trying to overwrite an existing test
  659. }
  660. test = !!(test());
  661. docElement.className += ' ' + (test ? '' : 'no-') + feature;
  662. ret[ feature ] = test;
  663. return ret; // allow chaining.
  664. };
  665. /**
  666. * Reset m.style.cssText to nothing to reduce memory footprint.
  667. */
  668. set_css( '' );
  669. modElem = inputElem = null;
  670. //>>BEGIN IEPP
  671. // Enable HTML 5 elements for styling in IE.
  672. // fyi: jscript version does not reflect trident version
  673. // therefore ie9 in ie7 mode will still have a jScript v.9
  674. if ( enableHTML5 && window.attachEvent && (function(){ var elem = document.createElement("div");
  675. elem.innerHTML = "<elem></elem>";
  676. return elem.childNodes.length !== 1; })()) {
  677. // iepp v1.6.2 by @jon_neal : code.google.com/p/ie-print-protector
  678. (function(win, doc) {
  679. var elems = 'abbr|article|aside|audio|canvas|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video',
  680. elemsArr = elems.split('|'),
  681. elemsArrLen = elemsArr.length,
  682. elemRegExp = new RegExp('(^|\\s)('+elems+')', 'gi'),
  683. tagRegExp = new RegExp('<(\/*)('+elems+')', 'gi'),
  684. ruleRegExp = new RegExp('(^|[^\\n]*?\\s)('+elems+')([^\\n]*)({[\\n\\w\\W]*?})', 'gi'),
  685. docFrag = doc.createDocumentFragment(),
  686. html = doc.documentElement,
  687. head = html.firstChild,
  688. bodyElem = doc.createElement('body'),
  689. styleElem = doc.createElement('style'),
  690. body;
  691. function shim(doc) {
  692. var a = -1;
  693. while (++a < elemsArrLen)
  694. // Use createElement so IE allows HTML5-named elements in a document
  695. doc.createElement(elemsArr[a]);
  696. }
  697. function getCSS(styleSheetList, mediaType) {
  698. var a = -1,
  699. len = styleSheetList.length,
  700. styleSheet,
  701. cssTextArr = [];
  702. while (++a < len) {
  703. styleSheet = styleSheetList[a];
  704. // Get css from all non-screen stylesheets and their imports
  705. if ((mediaType = styleSheet.media || mediaType) != 'screen') cssTextArr.push(getCSS(styleSheet.imports, mediaType), styleSheet.cssText);
  706. }
  707. return cssTextArr.join('');
  708. }
  709. // Shim the document and iepp fragment
  710. shim(doc);
  711. shim(docFrag);
  712. // Add iepp custom print style element
  713. head.insertBefore(styleElem, head.firstChild);
  714. styleElem.media = 'print';
  715. win.attachEvent(
  716. 'onbeforeprint',
  717. function() {
  718. var a = -1,
  719. cssText = getCSS(doc.styleSheets, 'all'),
  720. cssTextArr = [],
  721. rule;
  722. body = body || doc.body;
  723. // Get only rules which reference HTML5 elements by name
  724. while ((rule = ruleRegExp.exec(cssText)) != null)
  725. // Replace all html5 element references with iepp substitute classnames
  726. cssTextArr.push((rule[1]+rule[2]+rule[3]).replace(elemRegExp, '$1.iepp_$2')+rule[4]);
  727. // Write iepp custom print CSS
  728. styleElem.styleSheet.cssText = cssTextArr.join('\n');
  729. while (++a < elemsArrLen) {
  730. var nodeList = doc.getElementsByTagName(elemsArr[a]),
  731. nodeListLen = nodeList.length,
  732. b = -1;
  733. while (++b < nodeListLen)
  734. if (nodeList[b].className.indexOf('iepp_') < 0)
  735. // Append iepp substitute classnames to all html5 elements
  736. nodeList[b].className += ' iepp_'+elemsArr[a];
  737. }
  738. docFrag.appendChild(body);
  739. html.appendChild(bodyElem);
  740. // Write iepp substitute print-safe document
  741. bodyElem.className = body.className;
  742. // Replace HTML5 elements with <font> which is print-safe and shouldn't conflict since it isn't part of html5
  743. bodyElem.innerHTML = body.innerHTML.replace(tagRegExp, '<$1font');
  744. }
  745. );
  746. win.attachEvent(
  747. 'onafterprint',
  748. function() {
  749. // Undo everything done in onbeforeprint
  750. bodyElem.innerHTML = '';
  751. html.removeChild(bodyElem);
  752. html.appendChild(body);
  753. styleElem.styleSheet.cssText = '';
  754. }
  755. );
  756. })(window, document);
  757. }
  758. //>>END IEPP
  759. // Assign private properties to the return object with prefix
  760. ret._enableHTML5 = enableHTML5;
  761. ret._version = version;
  762. // Remove "no-js" class from <html> element, if it exists:
  763. docElement.className = docElement.className.replace(/\bno-js\b/,'')
  764. + ' js '
  765. // Add the new classes to the <html> element.
  766. + classes.join( ' ' );
  767. return ret;
  768. })(this,this.document);