0

I am working on my 1st website using bootstrap. I'm using javascript to center my images vertically, however what I noticed that sometimes javascript is loaded before some of the images, so those images aren't centered.

Html:

<div class="hidden-xs col-sm-3 text-center">
        <img src="../img/body/gear.png" alt="gear.png" class="scale-icon pull-center" />
</div>

JavaScript:

<script>
function pullCenter() {
        $(this).css('margin-top', $(this).parent().parent().height()/2-$(this).height()/2);
    }
    $('.pull-center').each(pullCenter);
    $( window ).resize(function() {
        $('.pull-center').each(pullCenter);
    });
</script>

How can I make sure that all images are already loaded before executing

 $('.pull-center').each(pullCenter);

Java script is at the bottom of html.

user2821023
  • 511
  • 1
  • 8
  • 22

2 Answers2

0

I'd personally fire your aligning code on a load event for each image object.

Just add an event listener for your images (you can do it on a class, so not every image tag gets ordered).

When the event is fired pass the object to your aligning method.

This way, the loading of the images will fire the aligning code.

If the aligning of any image may interfere with the aligning of others, I mean, if the order in which you align different images can alter the way they are displayed in the end, then your best option is to fire the code after the whole page is loaded, using a document.ready event for jQuery, as Aleem has stated, for example.

Bardo
  • 2,470
  • 2
  • 24
  • 42
  • You cannot add an event listener to an image that has inline src set. The load will likely trigger before your event listener is assigned. – mplungjan Oct 22 '15 at 09:59
-1

You can use jQuery to call functions if image is loaded or if there is an error:

$("<img/>")
  .on('load', function() { console.log("image loaded correctly"); })
  .on('error', function() { console.log("error loading image"); })
  .attr("src", $(originalImage).attr("src"))
;
Sebastian Schneider
  • 4,896
  • 3
  • 20
  • 47