From e1be31bf1fa66a414a0543772ed251b42e8be22b Mon Sep 17 00:00:00 2001 From: Scott Jehl Date: Thu, 6 Jun 2013 15:42:47 +0100 Subject: [PATCH] append the img element to the active data-src container, allowing for simple css targeting, perhaps similar to how picture itself would work. --- README.md | 20 ++++++++++++++++++++ picturefill.js | 7 ++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 993bc4a4..e6c1af59 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,26 @@ Notes on the markup above... * Each `[data-src]` element can have an optional `[data-media]` attribute to make it apply in specific media settings. Both media types and queries can be used, like a native `media` attribute, but support for media _queries_ depends on the browser (unsupporting browsers fail silently). * The `matchMedia` polyfill (included in the `/external` folder) is necessary to support the `data-media` attribute across browsers (such as IE9), even in browsers that support media queries, although it is becoming more widely supported in new browsers. * The `noscript` element wraps the fallback image for non-JavaScript environments, and including this wrapper prevents browsers from fetching the fallback image during page load (causing unnecessary overhead). Generally, it's a good idea to reference a small mobile optimized image here, as it's likely to be loaded in older/underpowered mobile devices. + +### How the `img` is appended + +Upon finding a matching `span[data-src]` element, picturefill will generate an `img` element referencing that `span`'s `data-src` attribute value and append the `img` to the active, matching `span[data-src]` element. This means you can target CSS styles specific to the active image based on the breakpoint that is in play, perhaps by adding a class to each span. For example, if you have the following markup... + +```html + + + + +```` + +...then you could write styles specific to each of the images, which may be handy for certain layout situations. + +```css + [data-picture] .sml { /* Styles for the small image */ } + [data-picture] .med { /* Styles for the medium image */ } + [data-picture] .lrg { /* Styles for the large image */ } +```` + ### HD Media Queries diff --git a/picturefill.js b/picturefill.js index eb244d76..0ba0e782 100644 --- a/picturefill.js +++ b/picturefill.js @@ -28,16 +28,17 @@ var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ]; if( matches.length ){ + var matchedEl = matches.pop(); if( !picImg ){ picImg = w.document.createElement( "img" ); picImg.alt = ps[ i ].getAttribute( "data-alt" ); - ps[ i ].appendChild( picImg ); } - picImg.src = matches.pop().getAttribute( "data-src" ); + picImg.src = matchedEl.getAttribute( "data-src" ); + matchedEl.appendChild( picImg ); } else if( picImg ){ - ps[ i ].removeChild( picImg ); + picImg.parentNode.removeChild( picImg ); } } }