Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active March 23, 2021 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronsummers/c1dc8e51d858355fff7c7ee0e14b7569 to your computer and use it in GitHub Desktop.
Save aaronsummers/c1dc8e51d858355fff7c7ee0e14b7569 to your computer and use it in GitHub Desktop.
Responsive background image script
<!--
Each image is added to a new data attribute large, medium and small.
Add the image url followed by a space and then the width to apply the image.
Finally so the js can call the images add the responsive-bg class.
-->
<div class="elab_responsive-bg "
data-large="/images/hero-1440x360.jpg 1024"
data-medium="/images/hero-768x360.jpg 768"
data-small="/images/hero-375x310.jpg 320">
</div>
(function($) {
if ( $('.elab_responsive-bg').length ) {
$('.elab_responsive-bg').each(function() {
var $window = $(window),
$this = $(this),
large = $this.data('large').split(' '),
medium = $this.data('medium').split(' '),
small = $this.data('small').split(' ');
if ( $window.width() >= large[1] ) {
$this.css('background-image', 'url(' + large[0] + ')');
console.log('responsive loading... ' + large[1]);
} else if ( $window.width() >= medium[1] ) {
$this.css('background-image', 'url(' + medium[0] + ')');
console.log('responsive loading... ' + medium[1]);
} else if ( $window.width() >= small[1] ) {
$this.css('background-image', 'url(' + small[0] + ')');
console.log('responsive loading... ' + small[1]);
} else {
$this.addClass('image-not-found');
}
})
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment