0

I have very simple code snippet which is intended to vertically center img inside li. Work's good in every browser but Chrome where browser see always the same vale as a result of calculation which is not possible.

JavaScript:

$(function(){
    var $li = $("div.operators ul > li");
    var $img;
    var liHeight = $li.height();
    var imgHeight = '';
    var addPadding = '';

    $li.each(function(){
        $img = $(this).children().children("img");
        imgHeight = $img.height();

        imgHeight += 3;

        if(!isNaN(imgHeight))
        {
            addPadding = (liHeight - imgHeight) / 2;
            $img.css("padding-top", addPadding + "px")
        }
    });
});

Html:

<div class="operators">
    <ul>
        <li>
            <div class="content">
                <img src="logo3.gif">
            </div>
        </li>
        <li>
            <div class="content">
                <img src="logo5.gif">
            </div>
        </li>
            <li>
            <div class="content">
                <img src="logo.gif">
        </div>
    </ul>
</div>

I'm using jQuery v@1.8.0.

andand
  • 15,638
  • 9
  • 48
  • 76
webrama.pl
  • 1,770
  • 22
  • 34
  • You have missed the last closed `` element. Also, add `;` for this code at the end: `$img.css("padding-top", addPadding + "px")` – Pavlo Feb 19 '14 at 10:11
  • 1
    you need to wait for your images to finish loading so either do it on window.load or [this may help](http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached). – Pete Feb 19 '14 at 10:14
  • 1
    @Pavlo the `;` isn't necessary there as it's followed by a `}`. – James Donnelly Feb 19 '14 at 10:17
  • Yes. Window.load works. Look like Chrome's JS engine is too fast :) – webrama.pl Feb 19 '14 at 10:18
  • @JamesDonnelly a `;` is always necessary. Probably in this case not, but what if in the future he will add another line of code after that? – Pavlo Feb 19 '14 at 10:20
  • 1
    `;` is optional. Sure, it's good practice to always add them, but it's not *necessary*. – James Donnelly Feb 19 '14 at 10:23

1 Answers1

0

Chrome JavaScript engine is considered as the fastest one. Probably browser is looping through li before images are fully loaded so try (as @Pete suggested):

 $(window).load(function(){
       ...
    });

This should help.

webrama.pl
  • 1,770
  • 22
  • 34