While working on a Sitefinity Image Gallery control, I came across an issue using jQuery.width() and height() methods on the loaded images from the Sitefinity Images & Documents module. For most of the images, both the returned values for width and height were returning 0. After loading different pieces from the DOM, I realized that most (if not all) of the images were not actually getting loaded into the DOM before trying to find the width and height.
The solution was to, instead of using document.ready(), use window.load().
Original, non-working solution used the document.ready() function as below:
<script type="text/javascript">
$(document).ready(function () {
$(".thumb img").each(function () {
$(this).load();
var width = $(this).width();
var height = $(this).height();
$(this).css({ 'margin-left': '50%', 'margin-top': '50%' });
$(this).css({ 'left': '-' + ((width) / 2) + 'px', 'top': '-' + ((height) / 2) + 'px' });
});
});
</script>
The fix and working solution is to use the window.load() function as below:
<script type="text/javascript">
$(window).load(function () {
$(".thumb img").each(function () {
$(this).load();
var width = $(this).width();
var height = $(this).height();
$(this).css({ 'margin-left': '50%', 'margin-top': '50%' });
$(this).css({ 'left': '-' + ((width) / 2) + 'px', 'top': '-' + ((height) / 2) + 'px' });
});
});
</script>