Skip to content

Instantly share code, notes, and snippets.

@sebbdk
Last active May 26, 2016 11:34
Show Gist options
  • Save sebbdk/6dc44ace2a48a0aeb6667b4ca9a8d4bb to your computer and use it in GitHub Desktop.
Save sebbdk/6dc44ace2a48a0aeb6667b4ca9a8d4bb to your computer and use it in GitHub Desktop.
magic code
<div class="responsive-background" data-src="intro/introslide2.jpg"></div>
<script>
var resizeTimer;
var resizing = false;
var startWidth = 0;
var loadedImages = [];
var maxWidth = window.innerWidth;
$(window).on('resize', function(e) {
resizing = true;
if(!resizing) {
startWidth = window.innerWidth;
}
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
resizing = false;
if(maxWidth < window.innerWidth) {
adjustBackgroundImage();
maxWidth = window.innerWidth;
}
}, 250);
});
function adjustBackgroundImage() {
$.cloudinary.config({ cloud_name: 'www-bungalowcph-com'})
$('.responsive-background').each(function() {
var self = this;
var image = $(this).attr('data-src');
var w = $(this).outerWidth();
var h = $(this).outerHeight();
var url = jQuery.cloudinary.url(image, { width: w, height: h, crop: 'fill' });
loadedImages[url] = new Image();
loadedImages[url].src = url;
loadedImages[url].onload = function() {
$(self).css('background-image', 'url("' + url + '")');
};
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment