Created
July 7, 2015 04:54
-
-
Save dannymidnight/984463176485ee663948 to your computer and use it in GitHub Desktop.
Responsive background image
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
import Viewport from './viewport'; | |
import $ from 'jquery'; | |
export default function createResponsiveBgImages() { | |
const viewport = new Viewport(); | |
$('[data-image]').each((idx, el) => { | |
let images = {}; | |
let data = $(el).data(); | |
Object.keys(data).forEach((key) => { | |
let match = key.match(/image(.*)/); | |
if (match) { | |
let size = match[1].toLowerCase(); | |
images[size] = data[match[0]]; | |
} | |
}); | |
viewport.on('change', () => { | |
if (viewport.inSize(Object.keys(images))) { | |
$(el).css('background-image', `url(${images[viewport.size]})`); | |
} else { | |
$(el).css('background-image', `url(${data.image})`); | |
} | |
}); | |
viewport.handleResize(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example markup
<div data-image="default.jpg" data-image-small="small.jpg" data-image-large="large.jpg" />