Javascript height issue

I'm using javascript to add either the class vertical or horizontal to all image articles on a page. I'm having the problem that the code is working, but it's ALWAYS adding .horizontal to the article class, even photos that should have .vertical (posts that contain images larger than 450px high). Any help would be appreciated.

$('img.photo').each(function(){
            if($(this).height() > 450) { 
                $(this).closest('article').addClass('vertical'); 
            } else {
                $(this).closest('article').addClass('horizontal'); 
            }
        });

Example: http://blog.jamescharless.com/ The first photo of the boy is way more than 450px tall but it doesn't have the class of vertical, instead it has horizontal.

Upvotes: 0

Views: 73

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Two possible reasons the height is not as expected

  1. The image is not yet loaded and does not have a defined height in CSS
  2. The image is not yet revealed (display: none)

Your code could utilize the load callback, and should also check that the image is not :hidden.

$(function(){
    $('img:not(:hidden)').load(function(){
        // logic
    });
});

Upvotes: 3

ori
ori

Reputation: 7847

Try changing .each to .load, so that the function is called for each image once it's loaded:

$('img.photo').load(function(){
            if($(this).height() > 450) { 
                $(this).closest('article').addClass('vertical'); 
            } else {
                $(this).closest('article').addClass('horizontal'); 
            }
        });

Upvotes: 1

Related Questions