Is there a way to retrieve the height of an image and adjust its parent container height to be automatic?

Is there a way to achieve the following using pure JavaScript instead of jQuery?

I want to find the height of an image within a figure element and if the image's height is less than 200 pixels, I need to set its container's (parent's) height to auto.

The jQuery code provided works as expected, but I am interested in accomplishing this using plain JavaScript.

Check out the 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" );
    }
  });
});

Answer №1

const adjustImageHeight = () => {
    window.onload = function () {
        [].forEach.call( document.querySelectorAll('.imgH'), function(node, i) {
            if (node.clientHeight < 200) {
                node.parentNode.style.height = 'auto';    
            }
        });
    }
}

adjustImageHeight();
  • document.querySelectorAll('.imgH') - retrieves nodes with the class 'imgH',
  • node.clientHeight - determines the height of the image
  • node.parentNode.style.height - adjusts the height of the parent node, which in this case is not the figure element

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

Answer №2

It seems like you're saying that the jQuery version is functional, but you prefer to use regular JavaScript. If that's the case, you can achieve the same result with the following code:

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

This code snippet is functionally equivalent.

Answer №3

Consider using the following approach:

HTML

<div class="picture-wrapper">

/* the image will be inserted here */

</div>

JavaScript

$('.picture-wrapper').each(function() {
  if ($(this).find('img').length < 400) {
    $(this).css({'height': 'auto'});
  }
});

Answer №4

Based on my recollection:

  • To retrieve all the image nodes, you can utilize document.querySelector.
  • The naturalHeight and naturalWidth properties will provide you with the calculated height and width of the images.
  • You can access the parent of the image node using the parentNode property. Apply the necessary styles and your task will be complete.

Update: After reviewing Dave Walker's response, I'd like to add that naturalWidth and naturalHeight will supply you with the original dimensions of the image. To obtain the computed/displayed height and width, you should use offsetHeight and offsetWidth.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

Select three unique numbers at random from the total number of elements in the array

I currently possess an array containing a variety of objects. At present, there are 21 objects in this array, although this number is subject to change. To iterate through the array and generate the necessary content, I am implementing the following code ...

The JavaScript function is not functioning properly, whereas another function is working as intended

I have created a HTML form with 2 buttons and a table. Each row in the table consists of a checkbox and 2 text fields. The buttons allow users to add and remove rows from the table. The remove button only applies to rows where their checkbox is checked. T ...

The min-width of 100vh is functioning properly on mobile devices, however, it is not working as expected on PCs when set to 100

When using 100vh, it only works on mobile or if you narrow the width of your web browser on a PC. If the window/width is set at 100%, the image may appear too tall and cause the div class "mars" to overflow the viewport. Unfortunately, screenshots cannot ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

Creating easy nested list views in React Native using object data structures

I am working with an array of objects that contains user data like this: const userList = [ { "firstName": "John", "lastName": "Doe", "date": "19 March 2018" }, { "firstName": "Anna", ...

Enhance the v-autocomplete dropdown with a personalized touch by adding a custom

Currently utilizing the v-autocomplete component from Vuetify, and I am interested in incorporating a custom element into its dropdown menu. You can see the specific part I want to add highlighted with a red arrow in this screenshot: This is the current s ...

Styling emails with CSS: Tips for customizing fonts

I've been experimenting with setting a personalized font for an email. Within the HTML code of the email, I included the fonts using this snippet: <head> <style> /* latin-ext */ @font-face { font-family: &ap ...

Using JavaScript to pass a value from an input field to a href attribute

I am currently working on a scenario where, upon clicking on an input field, the value is passed to a URL and the corresponding radio button is checked. This way, I can share the URL with someone else. Unfortunately, I have hit a roadblock in my progress: ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

Automatically calculate the product of two columns in a gridview

Greetings, I am currently working on a project that involves calculating values from two textboxes within a gridview and displaying the result in a third textbox using JavaScript. The calculation should occur as soon as a value is entered into the second ...

NodeJS: Encountering an issue with retrieving the cart ID - receiving

I am having issues with the cart variable, even though I defined it using await cartsRepo.create({ items: [] });. For some reason, I keep getting undefined when trying to access cart. I suspect that the request is not resolving properly, which might be ca ...

How can I install fs and what exactly does it do in JavaScript?

As a beginner in the world of JavaScript, I am struggling with what seems like a basic issue. In my journey to develop some JavaScript code and utilize sql.js, I keep encountering an error at this line: var fs = require('fs'); This error is due ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

PhoneGap switches up the error type with each consecutive run

Why does PhoneGap change errors after every time it is compiled? Sometimes it runs without any issues, but then the same code throws strange errors like parse error or function not found, even though no changes were made to the code. Here is the code that ...

Connecting to a specific mui-tab with react-router-dom

How can I link to a specific tab in my material ui-based tabs setup within a React application? I want to be able to navigate directly to a particular tab when landing on the page, but I'm struggling with integrating this functionality. Is there a way ...

Positioning Problems with Popups

I have been facing an issue with the positioning of a popup in my trivia game. Despite trying multiple solutions, I have not been able to achieve consistency. Here is a snippet of the HTML code: <div class="logo"> <img src="css/rio-40.png"/& ...