Skip to content

Instantly share code, notes, and snippets.

@vasilisvg
Created September 7, 2011 10:50
Show Gist options
  • Save vasilisvg/1200270 to your computer and use it in GitHub Desktop.
Save vasilisvg/1200270 to your computer and use it in GitHub Desktop.
Responsive context aware images without cookies or server logic
<!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>
@vasilisvg
Copy link
Author

Thanks for your explanations hpoom and mathiasbynens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment