basitmate
basitmate

Reputation: 81

How to get an image's height and set its parent height to auto?

How do I do the following without jQuery and with pure JavaScript:

What I'm trying to do is to get the height of the image within the figure element and if the image's height is less than 200 pixels than I want its container's (parent's) height to be set to auto.

The jQuery method below is working but I want to do this with JavaScript.

see fiddle here.

HTML

<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>

<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>

<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>

<figure>
<img class="imgH" height="250" width="250" src="/some_img.jpg"/> // This image height is less than 300 pixels.
</figure>

<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>

CSS

figure {
 width: 500px;
 height: 500px;
}

JavaScript (jQuery)

$(document).ready(function(){
  $(".imgH").each(function(){
    if( $(this).height() < 200 ) {
        $(this).parent().height( "auto" );
    }
  });
});

Upvotes: 1

Views: 951

Answers (4)

Oleksandr T.
Oleksandr T.

Reputation: 77512

window.onload = function () {
    [].forEach.call( document.querySelectorAll('.imgH'), function(node, i) {
        if (node.clientHeight < 200) {
            node.parentNode.style.height = 'auto';    
        }
    });
}
  • document.querySelectorAll('.imgH') - return nodes which has class imgH,
  • node.clientHeight - get image Height
  • node.parentNode.style.height - set Height to parent node, in out case parent not is figure

DEmo: http://jsfiddle.net/6tjn7675/4/

Upvotes: 1

Dave Walker
Dave Walker

Reputation: 3523

so a little bit confusing but are you saying that the jquery version is working but you want it in normal javascript?

If so something like:

    if( this.offsetHeight< 200 ) {
        var container = this.parentNode;
        container.style.height = "auto";
    }

Is an equivalent statement.

Upvotes: 1

wtflux
wtflux

Reputation: 63

From what I can remember:

  • You could use document.querySelector to get all the image nodes.
  • naturalHeight and naturalWidth properties will get you the computed height and width of the images.
  • parentNode property of the image node will get you the parent. Apply the required styles and you should be done.

Edit: Just saw Dave Walker's answer. naturalWidth and naturalHeight will give you the original height and width of the image. To get the computed/displayed height and width you must use offsetHeight and offsetWidth.

Upvotes: 0

Sleek Geek
Sleek Geek

Reputation: 4686

Try something like this:

HTML

<div class="image-container">

/* image goes here */

</div>

jQuery

$('.image-container').each(function() {
        if ($(this).find('img').length < 300 ) {
            $(this).css({'height' 'auto'});
        }
        });

Upvotes: 0

Related Questions