-4

I'm trying to get the width and height of certain images equal (or, more specific: the div around it), but somehow it doesn't seem to work.. Anyone who can help?

$('.a2paragraph .image img').each(function() {
    var img = $('.a2paragraph .image img');

    var h = img.height(),
        w = img.width();

    if (h > w) {
        img.parent().css('height', w);
    }
    else if (w < h) {
        img.parent().css('width', h);
    }


});

EDIT: changed the code, but still not working:

$('.a2paragraph .image img').each(function() {
    var img2 = $('.a2paragraph .image img');

    var h = img2.height(),
        w = img2.width();

    if (h > w) {
        img2.parent().css('height', w);
    }
    else if (h < w) {
        img2.parent().css('width', h);
    }


})
5
  • 3
    So you have an image with an id "img"? I doubt that is what you want. DOM does not have height() and width(). You are mixing up jQuery and DOM. May 31, 2016 at 14:07
  • Yeah it was just to test it, but that isn't the error though. May 31, 2016 at 14:08
  • 2
    Possible duplicate of How can I debug my JavaScript code?
    – Liam
    May 31, 2016 at 14:09
  • Error is the fact is your test is wrong May 31, 2016 at 14:09
  • h>w and w<h are the same condition.
    – RJM
    May 31, 2016 at 14:12

1 Answer 1

5
if (h > w) {
    img.parent().css('height', w);
}
else if (w < h) {
    img.parent().css('width', h);
}

The if and the else if conditions are the same. You're checking for h > w twice, just written in different orders.

5
  • 1
    plus it misses the case where h=w
    – Marc B
    May 31, 2016 at 14:09
  • @MarcB Does not matter since setting the opposite to equal the other is the same thing... May 31, 2016 at 14:10
  • Oh!! Haha wow that's stupid.. Thanks a lot. No it doesn't have to do anything when they're equal :) May 31, 2016 at 14:10
  • img contains all images and therefor returns always the height and width of the first image. Change it to var img = $(this) instead
    – Andreas
    May 31, 2016 at 14:15
  • @Andreas ah okay, thanks! Changed it but doesn't solve it though.. it just doesn't add the css to img.parent() ? May 31, 2016 at 14:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.