jQuery plugin designed to reload img elements' source images as CSS background images on their parent elements. This enables handy CSS features such as more responsive full-bleed images using the cover property, while maintaining the img as content with its alt attribute, etc. for search, accessibility, and ease of development.
https://codepen.io/fonstok/pen/WXpJxw
Just follow these steps to enable:
-
Include jQuery on your page.
<script src="http://code.jquery.com/jquery.min.js"></script>
-
Download and include jfImgToCSS after jQuery and before its first use.
<script src="jquery.jfImgToCSS.js"></script>
-
Init the plugin by attaching it to the img elements you want to be css background images.
$(".imgToCSS").jfImgToCSS();
The options are all CSS background properties.
Options and Defaults
- auto: 'true' If you'd prefer to set your own background css properites via traditional methods set this to false.
- target: The img element's parent This can be changed to another element.
- bgRepeat: 'no-repeat'
- bgSize: 'cover'
- bgPosition: 'center center'
- bgOrigin: 'padding-box'
- bgClip: 'border-box'
- bgAttachment: 'scroll'
- bgColor: 'transparent'
Options can be passed as arguments through the init function.
$('.imgToCSS').jfImgToCSS({
auto:'true',
bgRepeat: 'no-repeat',
bgSize: 'cover',
bgPosition: 'center center',
bgOrigin: 'padding-box',
bgClip: 'border-box',
bgAttachment: 'scroll',
bgColor: 'transparent',
});
Options can also be passed through data attributes in the opening of the attached element. Notice that the data attributes use dashes instead of camel case.
<img class="imgToCSS"
data-bg-repeat="repeat"
data-bg-size="100% auto"
data-bg-position="center"
alt="photo of a jungle"
src="images/jungle.jpg">
There are a few public functions that can be called at any time after init.
- destroy(): This deactivates the plugin.
- init(): This initiates the plugin, this gets called automatically.
$(".imgToCSS").data("jfImgToCSS").destroy();
$(".imgToCSS").data("jfImgToCSS").init();
- Only works with img elements, so you need to target those.
- Make sure its parent element has some sort of width and/or height or it will collapse.
<div class="column">
<img class="imgToCSS"
data-bg-repeat="repeat"
data-bg-size="100% auto"
data-bg-position="center"
alt="photo of a jungle"
src="images/jungle.jpg">
</div>
I used http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/ as a starting point for the plugin.