CSS object-fit fallback with plain JS

Developer
Size
4,895 Kb
Views
16,192

How do I make an css object-fit fallback with plain js?

Inspired by https://medium.com/@primozcigler/neat-trick-for-css-object-fit-fallback-on-edge-and-other-browsers-afbc53bbb2c3#.mtzhts9qe but with plain JS because I don't like using jQuery when it's not necessary.. What is a css object-fit fallback with plain js? How do you make a css object-fit fallback with plain js? This script and codes were developed by Luuk Lamers on 22 January 2023, Sunday.

CSS object-fit fallback with plain JS Previews

CSS object-fit fallback with plain JS - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>CSS object-fit fallback with plain JS</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" href="css/style.css">
</head>
<body> <script>/*! modernizr 3.3.1 (Custom Build) | MIT * * https://modernizr.com/download/?-objectfit !*/
!function(e,n,t){function r(e,n){return typeof e===n}function o(){var e,n,t,o,i,s,f;for(var a in h)if(h.hasOwnProperty(a)){if(e=[],n=h[a],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(o=r(n.fn,"function")?n.fn():n.fn,i=0;i<e.length;i++)s=e[i],f=s.split("."),1===f.length?Modernizr[f[0]]=o:(!Modernizr[f[0]]||Modernizr[f[0]]instanceof Boolean||(Modernizr[f[0]]=new Boolean(Modernizr[f[0]])),Modernizr[f[0]][f[1]]=o),g.push((o?"":"no-")+f.join("-"))}}function i(e){return e.replace(/([a-z])-([a-z])/g,function(e,n,t){return n+t.toUpperCase()}).replace(/^-/,"")}function s(e,n){return!!~(""+e).indexOf(n)}function f(e,n){return function(){return e.apply(n,arguments)}}function a(e,n,t){var o;for(var i in e)if(e[i]in n)return t===!1?e[i]:(o=n[e[i]],r(o,"function")?f(o,t||n):o);return!1}function u(e){return e.replace(/([A-Z])/g,function(e,n){return"-"+n.toLowerCase()}).replace(/^ms-/,"-ms-")}function l(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):b?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function p(){var e=n.body;return e||(e=l(b?"svg":"body"),e.fake=!0),e}function d(e,t,r,o){var i,s,f,a,u="modernizr",d=l("div"),c=p();if(parseInt(r,10))for(;r--;)f=l("div"),f.id=o?o[r]:u+(r+1),d.appendChild(f);return i=l("style"),i.type="text/css",i.id="s"+u,(c.fake?c:d).appendChild(i),c.appendChild(d),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(n.createTextNode(e)),d.id=u,c.fake&&(c.style.background="",c.style.overflow="hidden",a=S.style.overflow,S.style.overflow="hidden",S.appendChild(c)),s=t(d,e),c.fake?(c.parentNode.removeChild(c),S.style.overflow=a,S.offsetHeight):d.parentNode.removeChild(d),!!s}function c(n,r){var o=n.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;)if(e.CSS.supports(u(n[o]),r))return!0;return!1}if("CSSSupportsRule"in e){for(var i=[];o--;)i.push("("+u(n[o])+":"+r+")");return i=i.join(" or "),d("@supports ("+i+") { #modernizr { position: absolute; } }",function(e){return"absolute"==getComputedStyle(e,null).position})}return t}function m(e,n,o,f){function a(){p&&(delete z.style,delete z.modElem)}if(f=r(f,"undefined")?!1:f,!r(o,"undefined")){var u=c(e,o);if(!r(u,"undefined"))return u}for(var p,d,m,v,h,y=["modernizr","tspan"];!z.style;)p=!0,z.modElem=l(y.shift()),z.style=z.modElem.style;for(m=e.length,d=0;m>d;d++)if(v=e[d],h=z.style[v],s(v,"-")&&(v=i(v)),z.style[v]!==t){if(f||r(o,"undefined"))return a(),"pfx"==n?v:!0;try{z.style[v]=o}catch(g){}if(z.style[v]!=h)return a(),"pfx"==n?v:!0}return a(),!1}function v(e,n,t,o,i){var s=e.charAt(0).toUpperCase()+e.slice(1),f=(e+" "+w.join(s+" ")+s).split(" ");return r(n,"string")||r(n,"undefined")?m(f,n,o,i):(f=(e+" "+_.join(s+" ")+s).split(" "),a(f,n,t))}var h=[],y={_version:"3.3.1",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){h.push({name:e,fn:n,options:t})},addAsyncTest:function(e){h.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=y,Modernizr=new Modernizr;var g=[],C="Moz O ms Webkit",w=y._config.usePrefixes?C.split(" "):[];y._cssomPrefixes=w;var x=function(n){var r,o=prefixes.length,i=e.CSSRule;if("undefined"==typeof i)return t;if(!n)return!1;if(n=n.replace(/^@/,""),r=n.replace(/-/g,"_").toUpperCase()+"_RULE",r in i)return"@"+n;for(var s=0;o>s;s++){var f=prefixes[s],a=f.toUpperCase()+"_"+r;if(a in i)return"@-"+f.toLowerCase()+"-"+n}return!1};y.atRule=x;var _=y._config.usePrefixes?C.toLowerCase().split(" "):[];y._domPrefixes=_;var S=n.documentElement,b="svg"===S.nodeName.toLowerCase(),E={elem:l("modernizr")};Modernizr._q.push(function(){delete E.elem});var z={style:E.elem.style};Modernizr._q.unshift(function(){delete z.style}),y.testAllProps=v;var P=y.prefixed=function(e,n,t){return 0===e.indexOf("@")?x(e):(-1!=e.indexOf("-")&&(e=i(e)),n?v(e,n,t):v(e,"pfx"))};Modernizr.addTest("objectfit",!!P("objectFit"),{aliases:["object-fit"]}),o(),delete y.addTest,delete y.addAsyncTest;for(var T=0;T<Modernizr._q.length;T++)Modernizr._q[T]();e.Modernizr=Modernizr}(window,document);</script>	<div class="image">	<strong>1200x600</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/1200x600" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>400x300</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/400x300" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>300x400</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/300x400" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>100x100</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/100x100" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>10x10</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/10x10" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>250x250</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/250x250" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>500x250</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/500x250" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>250x500</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/250x500" class="post__featured-image">	</a>	</div>	</div>	<div class="image">	<strong>201x600</strong>	<div class="post__image-container">	<a href="blogpost.html">	<img src="http://placehold.it/201x600" class="post__featured-image">	</a>	</div>	</div> <script src="js/index.js"></script>
</body>
</html>

CSS object-fit fallback with plain JS - Script Codes CSS Codes

.image { display: inline-block; margin: 1em;
}
.image strong { display: block; text-align: center; width: 100%;
}
.post__image-container { width: 240px; height: 240px;
}
.post__image-container.compat-object-fit { position: relative; background-size: cover; background-position: center center;
}
.post__image-container.compat-object-fit > a { position: absolute; top: 0; bottom: 0; left: 0; right: 0;
}
.post__image-container.compat-object-fit .post__featured-image { display: none;
}
.post__featured-image { width: 240px; height: 240px; -o-object-fit: cover; object-fit: cover;
}

CSS object-fit fallback with plain JS - Script Codes JS Codes

/**
* helper function to check whether an element has a specific class
* @param {HTMLElement} el the element
* @param {string} className the class
* @return {boolean} whether the element has the class
*/
function hasClass(el, className) {	return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
}
/**
* helper function to add a class to an element
* @param {HTMLElement} el the element
* @param {string} className the class
*/
function addClass(el, className) {	if (el.classList) {	el.classList.add(className);	} else if (!hasClass(el, className)) {	el.className += ' ' + className;	}
}
var imgContainers;
var len;
if (!Modernizr.objectfit) {	imgContainers = document.querySelectorAll('.post__image-container');	len = imgContainers.length;	for (var i=0; i<len; i++) {	var $container = imgContainers[i],	imgUrl = $container.querySelector('img').getAttribute('src');	if (imgUrl) {	$container.style.backgroundImage = 'url(' + imgUrl + ')';	addClass($container, 'compat-object-fit');	}	}
}
CSS object-fit fallback with plain JS - Script Codes
CSS object-fit fallback with plain JS - Script Codes
Home Page Home
Developer Luuk Lamers
Username xaddict
Uploaded January 22, 2023
Rating 3.5
Size 4,895 Kb
Views 16,192
Do you need developer help for CSS object-fit fallback with plain JS?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Luuk Lamers (xaddict) Script Codes
Create amazing web content with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!