Skip to content

Instantly share code, notes, and snippets.

@silenzium
Last active November 4, 2019 04:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silenzium/69d20977b3555fd2d52c to your computer and use it in GitHub Desktop.
Save silenzium/69d20977b3555fd2d52c to your computer and use it in GitHub Desktop.
This is a simple fallback for the object-fit property on responsive images inside picture elements (with srcset and media-query sources). It hides the img on browsers that don't support object-fit and sets the current used image as a background-image with background-size:cover.
$(function() {
'use strict';
// the css selector for the container that the image should be attached to as a background-image
var imgContainer = '.cover-img picture';
function getCurrentSrc(element, cb)
{
var getSrc;
if (!window.HTMLPictureElement) {
if (window.respimage) {
respimage({
elements : [element]
});
}
else if (window.picturefill) {
picturefill({
elements : [element]
});
}
cb(element.src);
return;
}
getSrc = function()
{
element.removeEventListener('load', getSrc);
element.removeEventListener('error', getSrc);
cb(element.currentSrc);
};
element.addEventListener('load', getSrc);
element.addEventListener('error', getSrc);
if (element.complete) {
getSrc();
}
}
function setBgImage() {
$(imgContainer).each(function()
{
var $this = $(this), img = $this.find('img').get(0);
getCurrentSrc(img, function(elementSource)
{
$this.css('background-image', 'url(' + elementSource + ')');
});
});
}
if ('objectFit' in document.documentElement.style === false) {
$('html').addClass('no-objectfit');
$(window).resize(function()
{
setBgImage();
});
setBgImage();
}
});
.no-objectfit {
.cover-img {
picture {
background-position:50% 50%;
background-size:cover;
background-repeat:no-repeat;
}
img {
visibility:hidden;
}
}
}
@alxdxn
Copy link

alxdxn commented Feb 22, 2019

This was helpful, thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment