I have a simple page that loads a random image from an array and positions it centrally using negative margins in CSS. This currently works as all the images are the same size, but I would like to adapt the code so that it can accommodate images with varying dimensions.
Is it possible to calculate the height and width of an image at the array stage, then pass it through to the CSS/HTML to position it centrally? Here is the code I am currently working with – any help would be greatly appreciated.
HTML/CSS:
#content {
margin-top: -206px;
margin-left: -290px;
position: absolute;
top: 50%;
left: 50%;
width: auto;
height: auto;
}
<div id="content">
<img class="shuffle" src="" width="580" height="413" border="0" alt="" />
</div>
JQuery:
$(document).ready(function() { $('.shuffle').randomImage({path: 'images/'}); } );
(function($){ $.randomImage = { defaults: { path: 'images/', myImages: [ 'image01.jpg', 'image02.jpg','image03.jpg', 'image04.jpg', 'image05.jpg' ] } }
$.fn.extend({ randomImage:function(config) {
var config = $.extend({}, $.randomImage.defaults, config);
return this.each(function() {
var imageNames = config.myImages;
var imageNamesSize = imageNames.length;
var randomNumber = Math.floor(Math.random()*imageNamesSize);
var selectedImage = imageNames[randomNumber];
var fullPath = config.path + selectedImage;
$(this).attr( { src: fullPath, alt: selectedImage } );
});
}
});
})(jQuery);
This way:
I tested it in FF3.6 and it works.
Hope this helps. Cheers