I am seeking a solution for my webpage which currently loads a random image from an array and centers it using negative margins in CSS. While this method works fine with images of the same size, I am looking to modify the code so that it can handle images with different dimensions.
Is there a way to determine the height and width of an image at the array stage and then pass that information to the CSS/HTML to centrally position it? Below is the code I have been working on – any assistance would be highly appreciated.
Code Snippets:
#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);