Last active
March 23, 2021 11:49
-
-
Save aaronsummers/c1dc8e51d858355fff7c7ee0e14b7569 to your computer and use it in GitHub Desktop.
Responsive background image script
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
<!-- | |
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> |
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
(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