If Image Is Larger Than Container, Add Class

css, dom, html, jquery

Solution

See if this is what you are looking for.

Demo

var postWidth = $('.post').innerWidth();
$('.image img').removeClass('large, small') ;
    $('.image img').each(function() {

        var imageWidth = this.width;
        if (imageWidth > postWidth) {
            $(this).addClass('large');
        } else {
            $(this).addClass('small');
        }
    });

Problem

Ok so I've been at this for hours to no avail. What I want to do, is write a script that does the following: when an image is larger than it's container, it adds the class "large" to it. But, if an image is smaller than it's container, it adds the class small to it. Here's what I have so far: ``` $(window).load(function() { var screenImage = $('.image img'); // Create new offscreen image to test var theImage = new Image(); theImage.src = screenImage.attr('src'); // Get accurate measurements from that. var imageWidth = theImage.width; // Find post width var postWidth = $('.image').innerWidth(); $('.image img').each(function() { if (imageWidth > postWidth) { $('.image').find('img').addClass('large'); } else { $('.image').find('img').addClass('small'); } }); }); ``` Here's an example: http://jsfiddle.net/TheInfection/6fUgr/8 Instead, the end result for this script is that all images get the "large" class added to them. I've spent hours on Google, the jQuery website, etc. and I couldn't find the solution anywhere. Could someone help me?

Original source