user2912472
user2912472

Reputation: 15

jquery height/width if statement not working

$(window).load(function () {

    var $imgs = $('.boxInner img');

    $imgs.each(function () {
        var w = $(this).clientWidth;
        var h = $(this).clientHeight;

        if (w < h) { $(this).css("display","none"); };
    });
});

I've tried to write this in so many different ways to no avail. Basically, just look at the picture width and height. If the height is greater than the width turn the display to none. Somebody please help me figure this out. Should be so simple.

Upvotes: 0

Views: 391

Answers (3)

Robert
Robert

Reputation: 694

As I wrote in the comment, if you use window.load you have to wait for all ressources of the page will load. You can do it better with image.complete in combination with $(image).load(function() ... Or look for a image loader plugin there are much on the web.

Upvotes: 1

Tim Vermaelen
Tim Vermaelen

Reputation: 7069

// you want $(window).load() because you need to make sure your images are loaded before you can run this function
$(window).load(function (){
    var imgs = $('.boxInner img');

    if (imgs.length){
        $.each(imgs, function (index, item){
            var w = item.width(),
                h = item.height();

            if (w < h) { 
                item.css({display: "none"}); 
            }
        });
    }
});

Upvotes: 1

R. Oosterholt
R. Oosterholt

Reputation: 8090

either use the dom objects and its api:

$imgs.each(function () {
    var w = this.clientWidth;
    var h = this.clientHeight;

    if (w < h) { $(this).css("display","none"); };
});

or use jQuery objects and its api:

$imgs.each(function () {
    var w = $(this).width();
    var h = $(this).height();

    if (w < h) { $(this).css("display","none"); };
});

Upvotes: 2

Related Questions