I have a bunch of empty images that i need to set the src and positioning dynamically. All images have the same class but they will have different src, widths and height.
The values for src, width and height are stored as properties in objects that are named to match the id. In my setImage function I try and get them with id.width etc but they come up as undefined. How can i solve this?
jsfiddle here:
html:
<div class="img-holder">
<img class="imgs" id="img_11" />
</div>
<div class="img-holder">
<img class="imgs" id="img_12" />
</div>
<div class="img-holder">
<img class="imgs" id="img_13" />
</div>
javascript:
var img_11 = {
src: "http://lorempixel.com/output/animals-q-c-640-480-2.jpg",
width: 60,
height: 60
};
var img_12 = {
src: "http://lorempixel.com/output/sports-q-c-640-480-4.jpg",
width: 50,
height: 50
};
var img_13 = {
src: "http://lorempixel.com/output/people-q-c-640-480-2.jpg",
width: 100,
height: 100
};
function setImage(id) {
jQuery('#'+id).attr('src', id.src);
jQuery('#'+id).css({width: id.width});
jQuery('#'+id).css({height: id.height});
}
jQuery(document).ready(function () {
jQuery('.imgs').each(function () {
setImage(this.id);
});
});
ps. apologies if this is setup not very well and I welcome any improvements that can be made as I am still quite new on javascript and jquery.