Skip to content

Instantly share code, notes, and snippets.

@dstreet
Last active August 29, 2015 14:00
Show Gist options
  • Save dstreet/11182912 to your computer and use it in GitHub Desktop.
Save dstreet/11182912 to your computer and use it in GitHub Desktop.
jQuery.backgroundCover
/*
* jQuery.backgroundCover.js
* --------------------------------------------------------
* A polyfill for the background-size: cover CSS property.
*
* Copyright: David Street 2014
*/
(function($) {
$.fn.backgroundCover = function() {
this.each(function() {
var $this = $(this)
, re = /url\(["|']{0,1}(.+)["|']{0,1}\)/
, reMatches = []
, imgUrl = ''
, img;
reMatches = $this.css('backgroundImage').match(re);
// Must have a background image
if (reMatches.length == 0) return false;
// create a new image with the background-image url
imgUrl = reMatches[1];
$img = $('<img src="' + imgUrl + '">');
$img.css({
position: 'absolute',
top: 0,
width: '100%'
});
$(this).children().css({
position: 'relative'
});
$(this).css({
overflowY: 'hidden',
backgroundImage: 'none',
position: 'relative'
}).prepend($img);
});
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment