Cloudinary + jQuery
Using jQuery's data function to dynamically change a responsive image's src
by eitanp461
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://rawgit.com/cloudinary/cloudinary_js/master/js/jquery.cloudinary.js"></script>
<section
id="contentAfterIntro"
class="game-page-bckdCover"
style=" background: url('') center;
background-size:cover;">
<img
class="cld-responsive game-page-bckdImgCover"
id="backgroundAsset-15">
</section>
CSS
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
JavaScript
var i,
s,
RawDataSrcArray = [ 'https://res.cloudinary.com/demo/w_auto:200/sample.jpg',
'https://res.cloudinary.com/demo/w_auto:200/brown_sheep.jpg'
],
len = RawDataSrcArray.length;
var $image = $('#contentAfterIntro').find('#backgroundAsset-15');
for (i=0; i<len; ++i) {
(function(index) {
var s = RawDataSrcArray[index];
//console.log('url we send to cloudinary: '+s);
//send to img shell the first raw data-src
//which *automatically* generates src for img via CL. responsive
$image.data('src', s);
console.log('i have just added in data-src :'+$image.data('src'))
// alert('i have just added in data-src :'+$image.attr('data-src'))
//fire off a request to Cl. server to get responsive-adjusted url
//and download the image when it is returned
$.cloudinary.responsive($image);
console.log('i have just added in src :'+$image.attr('src'))
// alert('i have just added in src :'+$image.attr('src'))
//store
bgImage = $image.attr('src');
//prepare for netx loop iteration
//(does not work if data-src present when new attr('data-src')
//comes to kick in
//$image.removeAttr('data-src');
//$image.removeAttr('src');
//$image.attr('src-cache','');
})(i);
};
$("#contentAfterIntro").css( {
'backgroundImage': 'url('+bgImage+')'
});
//$image.attr('data-src', 'https://res.cloudinary.com/demo/w_auto:200/brown_sheep.jpg');
// $.cloudinary.responsive($image);
// General set up for Cl.
$(function() {
$.cloudinary.config( {cloud_name: 'demo'} );
//instantiate responsive CL. features
$.cloudinary.responsive({
});
});