Created
September 7, 2011 10:50
-
-
Save vasilisvg/1200270 to your computer and use it in GitHub Desktop.
Responsive context aware images without cookies or server logic
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
<!doctype html> | |
<!-- | |
WARNING! | |
You probably shouldn't use this technique since images never show up | |
if the script isn't loaded for one reason or another. Some reasons: | |
- The content is viewed using a RSS reader | |
- The content is viewed with a read-it-later service | |
- The user has a flaky connection (hotel wifi, Dutch train, etc) | |
--> | |
<meta charset="UTF-8"> | |
<title>Client side context aware responsive images</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<style> | |
.image-container { | |
width: 50%; | |
position: relative; | |
} | |
.image-container img { | |
display: block; | |
max-width: 100%; | |
} | |
</style> | |
<p>Here's <a href="http://nerd.vasilis.nl/code/responsive-images/noscript.html">a working example</a>.</p> | |
<!-- place all sources and real widths of all images in their data-attribute... --> | |
<div class="image-container" data-small="img/work-kills-small.jpg" data-medium="img/work-kills-medium.jpg" data-large="img/work-kills-large.jpg" data-small-width="350" data-medium-width="600" data-large-width="900" data-alt="work kills"> | |
<!-- ...create a noscript fallback for browsers without javascript... --> | |
<noscript> | |
<img src="img/work-kills-small.jpg" alt="work kills"> | |
</noscript> | |
</div> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> | |
<script> | |
// ...do things, and... | |
$('.image-container').each(function() { | |
var $this = $(this), | |
contentWidth = $this.width(), | |
theSource = | |
contentWidth < $this.data('small-width') ? $this.data('small') : | |
contentWidth < $this.data('medium-width') ? $this.data('medium') : | |
$this.data('large'); | |
$this.append('<img src="' + theSource + '" alt="' + $this.data('alt') + '">'); | |
}); | |
// ...tadaa! | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your explanations hpoom and mathiasbynens.