Last active
January 24, 2018 11:23
-
-
Save chrisboakes/700d22509d6cc7bce52393fc8250dbc5 to your computer and use it in GitHub Desktop.
Polyfill for browsers that do not support 'object-fit'
This file contains 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
/** | |
* Polyfill for browsers that do not support 'object-fit' | |
* Replaces any image with a 'data-object-fit' attribute with a div with a background-image | |
* @author Chris Boakes & Gemma Black | |
*/ | |
export class ObjectFitPolyfill { | |
constructor() { | |
this.dataSelector = '[data-object-fit]'; | |
this.backgroundSize = 'cover'; | |
this.cssClass = 'u-fill-image'; | |
if (!this.supportsObjectFit()) { | |
this.findImages(); | |
} | |
} | |
/** | |
* Find images, loop through them and replace with a div | |
*/ | |
findImages() { | |
[].slice.call(document.querySelectorAll(this.dataSelector)).forEach((item) => { | |
if (item.getAttribute('src')) { | |
let backgroundElement = this.createBackground( | |
item.getAttribute('src'), | |
item.getAttribute('class'), | |
item.getAttribute('id') | |
); | |
item.parentNode.replaceChild(backgroundElement, item); | |
} | |
}); | |
} | |
/** | |
* Our background-image container | |
* @param {string} src | |
* @param {string} tagClasses | |
* @param {string} tagId | |
* @return DOM element | |
*/ | |
createBackground(src, tagClasses, tagId) { | |
let backgroundElement = document.createElement('div'); | |
backgroundElement.style.backgroundImage = `url(${src})`; | |
backgroundElement.style.backgroundSize = this.backgroundSize; | |
backgroundElement.setAttribute('class', tagClasses + ' ' + this.cssClass) | |
if (tagId) { | |
backgroundElement.id = tagId; | |
} | |
return backgroundElement; | |
} | |
/** | |
* Detect whether we support object fit | |
* @return Boolean | |
*/ | |
supportsObjectFit() { | |
let testImg = typeof Image === 'undefined' ? {style: {'object-position': 1}} : new Image(); | |
return 'object-fit' in testImg.style; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment