Last active
November 4, 2019 04:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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(); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.no-objectfit { | |
.cover-img { | |
picture { | |
background-position:50% 50%; | |
background-size:cover; | |
background-repeat:no-repeat; | |
} | |
img { | |
visibility:hidden; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was helpful, thanks :)