3

I'm trying to apply some css to an image tag if the image is portrait, but for some reason .css() doesn't work in webkit. Basically the image tag doesn't get the 'style' property. Here's my code:

$(document).ready(function () {

    $('.listing .item .thumb img').each(function () {

          var _img = $(this);
          var _imgWidth = _img.outerWidth();
          var _imgHeight = _img.outerHeight();

          if (_imgHeight > _imgWidth) {
               _img.css('top', '-40%');
          }
    });
});

<div class="listing about">
    <div class="item">
        <a href="#" class="thumb">
            <img src="../_uploads/siteassets/images/thumb-carousel-2.jpg" />
            <span class="frame"></span>
        </a>
        <span class="snippet">
            <a href="#" class="title">Name Surname</a>
            <span class="date">Role in the company</span>
            <p class="description">Lorem ipsum dolor sit amet...</p>
        </span>
    </div>
</div>

I've tried to use .attr() instead of .css() but nothing. It doesn't work!

Any idea why?

2
  • top attrubute will work only when element have attrribute position with values absolute, relative or static. Also, I'm not sure top accepts percentage values. Commented Oct 25, 2011 at 11:30
  • the image is absolute positioned and yes it accept percentage, it works in all other browsers except webkit. Commented Oct 25, 2011 at 11:32

2 Answers 2

4

When .ready() is fired, the images probably don't have their dimensions set.

0 > 0 is false, so the top property is never set.

Use $(window).load(); instead, or this plugin.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! Still I don't get why using .ready() it works in all others browsers...Anyway thanks for your help! :)
If you explicitly set width and height attributes on your images (which I would recommend), your first version should work as well. Sometimes there are reasons you can't or don't want to do that, but I thought I'd mention it.
0

Webkit doesn't interpret the offset left or top beacuse the default position is none, add position relative. Gecko of mozilla interprete the offset when have position relative or not.

    <div style="position: relative; left: 10px;"></div>
    <script>
         alert($('div').offset().left);
    </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.