The title of this exercise is a real mouthful, but serves to highlight an interesting experiment: "What if we could use data tags to switch images?"
The immediate benefit of source shuffling is that it keeps CSS media queries out of the HTML markup (to see what I mean, take a look at the HTML code used in Working with the <picture> tags in the next section.)
It's an interesting concept and one you may want to consider using; to see how it works, we'll use an adapted version of an example created by the UX designer Jordan Moore. This uses JavaScript-based Conditional CSS library by Jeremy Keith to great effect. To see what I mean, let's get going on a demo to see how it works:
Our journey through this demo starts with setting up the markup needed. In a new file, add the following and save it as
datatags.html
in the root of our project area:<!DOCTYPE html> <html> <head> <title>Responsive Images using data- tags - Demo</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="css/datatags.css"> <script src="js/jquery.min.js"></script> <script src="js/onmediaquery.min.js"></script> <script src="js/datatags.js"></script> </head> <body> <img class="thumbnail" src="img/small.jpg" data-medium="img/ medium.jpg" data-large="img/large.jpg" alt="Responsive images example"> </body> </html>
We now need a handful of accompanying files. From the code bundle, extract
small.jpg
,medium.jpg
, andlarge.jpg
and save these to theimg
subfolder in our project folder.Next comes the three JavaScript files that we need:
jquery.min.js
,onmediaquery.min.js
, anddatatags.js
should be extracted from the code download and saved into thejs
subfolder of our project area.Finally, we need some styling. In a new file, add the following and save it as
datatags.css
in ourcss
subfolder:img { max-width: 100%; } body:after { content: "global"; display: none; } @media screen and (min-width: 35em) { body:after { content: "tablet"; display: none; } } @media screen and (min-width: 56em) { body:after { content: "desktop"; display: none; } }
We're all set. If all is well, we should see our small image appear first followed immediately by either of the large ones, depending on the size of our browser window.
The key to note in this demo is that we will only see the small.jpg
image on mobile devices where the viewport is already smaller. On larger devices and desktops, either the medium.jpg
or large.jpg
images will be shown instead as dictated by the media query in effect.