Last active
October 19, 2017 18:06
-
-
Save ummdorian/9e0b978efbf9191d43b4a01e2b5f7abd to your computer and use it in GitHub Desktop.
Responsive Background Image Swapping
This file contains hidden or 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
<div | |
class="featured-media featured-media--full-height featured-media--align-center clearfix background-image-swap" | |
style="background-image:url('/sites/default/files/styles/600x400/public/2017-10/maxresdefault.jpg?itok=E5qxr2Dx');" | |
data-src-set=" | |
/sites/default/files/styles/2400x1600/public/2017-10/maxresdefault.jpg?itok=F7dLgnBM|all and (min-width: 1800px)| | |
/sites/default/files/styles/1800x1200/public/2017-10/maxresdefault.jpg?itok=iiH_TyjT|all and (min-width: 1201px) and (max-width: 1799px)| | |
/sites/default/files/styles/1200x800/public/2017-10/maxresdefault.jpg?itok=a5RsL9YX|all and (min-width: 961px) and (max-width: 1200px)| | |
/sites/default/files/styles/900x600/public/2017-10/maxresdefault.jpg?itok=tlhEVdgF|all and (min-width: 601px) and (max-width: 960px)| | |
/sites/default/files/styles/600x400/public/2017-10/maxresdefault.jpg?itok=E5qxr2Dx|| | |
" | |
> | |
</div> | |
<script type="text/javascript"> | |
(function swapBackgroundImages(){ | |
jQuery('.background-image-swap').each(function(){ | |
var imageStyles = jQuery(this).attr('data-src-set').split('|'); | |
for(i=0;i<imageStyles.length;i++){ | |
if(isEven(i)){ | |
var query = Modernizr.mq(imageStyles[i+1].trim()); | |
if (query) { | |
console.log(imageStyles[i+1].trim()); | |
console.log(imageStyles[i].trim()); | |
//console.log(this); | |
jQuery(this).attr('style',"background-image:url('"+imageStyles[i].trim()+"');"); | |
break; | |
} | |
} | |
} | |
}); | |
})(); | |
function isEven(n) { | |
n = Number(n); | |
return n === 0 || !!(n && !(n%2)); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment