Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
}
}
@alexdixonco

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.