Retrieve the current width and height of an image after the maximum width and height constraints have been applied

Check out this example

The HTML:

<div class="container">
    <img src="http://placehold.it/500x500" alt="500x500" />
</div>
<div class="container">
    <img src="http://placehold.it/100x500" alt="100x500" />
</div>
<div class="container">
    <img src="http://placehold.it/500x100" alt="500x100" />
</div>
<div class="container">
    <img src="http://placehold.it/500x800" alt="500x800" />
</div>
<div class="container">
    <img src="http://placehold.it/800x500" alt="800x500" />
</div>
<div class="container">
    <img src="http://placehold.it/100x100" alt="100x100" />
</div>
<div class="container">
    <img src="http://placehold.it/200x100" alt="200x100" />
</div>​

CSS Styles:

div.container { width: 200px; height: 200px; line-height: 200px; overflow: hidden; border: 10px solid white; box-shadow: 0 1px 8px #BBB; margin: 10px; text-align: center; }
div.container img { position: relative; vertical-align:middle; }
div.container img.wide { max-height: 100%; }
div.container img.tall { max-width: 100%; }
div.container img.square { max-width: 100%; }​

Javascript Functionality:

$(window).load( function(){
var $imgs = $("div.container img");

$imgs.each( function(){
    var cW = $(this).parent().width();
    var cH = $(this).parent().height();
    var w = $(this).width(); //I want the CURRENT width, not original!!
    var h = $(this).height(); //I want the CURRENT height, not original!!
    var dW = w - cW;
    var dH = h - cH;

    console.log( cW + " " + cH + " " + w + " " + h + " " + dW + " " + dH );

    if ( w > h ){ 
        $(this).addClass("wide");
        $(this).css("left",  -dW/2);
    }
    else if ( w < h ){
        $(this).addClass("tall");
        $(this).css("top",  -dH/2);
    }
    else { $(this).addClass("square"); }                    
});
});​

In this code, a JavaScript function adds classes to images based on their proportions and resizes them. However, getting the resized image's dimensions after applying CSS rules like max-width and max-height has been challenging.

If you have any suggestions on how to retrieve the dimensions consistently without using timers or intervals, it would be greatly appreciated!

Thank you!

Answer №1

Take a look at this jsfiddle. The goal is to determine the width and height before applying a class with max-height/max-width, rather than after.

Here is some sample code to test (check the second console.log):

$(window).load( function(){
    var $imgs = $("div.container img");

    $imgs.each( function(){
        var cW = $(this).parent().width();
        var cH = $(this).parent().height();
        var w = $(this)[0].clientWidth; //I want the CURRENT width, not original!!
        var h = $(this)[0].clientHeight; //I want the CURRENT height, not original!!
        var dW = w - cW;
        var dH = h - cH;

        console.log( cW + " " + cH + " " + w + " " + h + " " + dW + " " + dH );

        if ( w > h ){ 
            $(this).addClass("wide");
            $(this).css("left",  -dW/2);
        }
        else if ( w < h ){
            $(this).addClass("tall");
            $(this).css("top",  -dH/2);
        }
        else { $(this).addClass("square"); }     
        var w = $(this).width(); //I want the CURRENT width, not original!!
        var h = $(this).height(); //I want the CURRENT height, not original!!
        console.log( w + " " + h );

    });
});​

width(), outerWidth - this always return current width.

naturalWidth/naturalHeight - this is to get an original,like with no any styles applied, width/height of image (available for IMG tag only in newer browsers)

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

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...

The data retrieved by the $.getJSON method is not displaying as a line graph

I am currently dealing with two files searh_journal.php <script type="text/javascript"> function submitForm() { var form = document.myform; var dataString = $(form).serialize(); $.ajax({ type: 'POST', url: & ...

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

What is the best way to align two HTML elements in a single column?

I need to adjust the layout of an existing <td> in order to display a checkbox and one additional field on the same line. The current setup places these elements on separate lines. Below is the provided HTML code: <!DOCTYPE html> <html> ...

Obtain the length of a sound file in .wav format

Can anyone suggest a way to incorporate a waveform or horizontal bar on a website that displays the duration of a WAV file in seconds using HTML text? For instance, for a 60-second WAV file: I'm open to any ideas. ...

Selections made from the dropdown menu will automatically generate additional fields in the

The code I'm working with is too lengthy to post in its entirety, so here is the JSFiddle link instead: https://jsfiddle.net/c0ffee/pew9f0oc/1/ My specific issue pertains to this screenshot: https://i.sstatic.net/swLqN.png Upon clicking on the dro ...

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

bootstrap3 container alignment

I encountered a challenge while attempting to right-align multiple Bootstrap 3 containers in a straightforward manner. Despite my efforts, achieving this proved to be more complex than expected. In essence, I faced an issue where aligning the text box with ...

Jest encounters an error when a third-party function is invoked on a jQuery selector

I am experiencing an issue with my react component that is utilizing the dataTable() function from datatables.js on a jQuery selector. Even though I have set up a jest test component for testing, the tests are failing and throwing the following error. ● ...

Exploring ways to obtain the value of an unchecked checkbox in CodeIgniter

I am currently working on an attendance system using CodeIgniter. I have a list of checkboxes and I have successfully managed to insert the checked data into the database. However, I am now trying to figure out how to insert the unchecked data into the dat ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Problem with CSS multi-level dropdown navigation in a vertical layout

I am in the process of creating a navigation menu with dropdown menus, which are working correctly. Now, I would like to add another sub-menu drop down inside dropdown 1, but I am having trouble getting it to function properly. How can I make Sub Menu 1 ac ...

Assist me with Twitter

Seeking assistance with a coding issue related to displaying Twitter posts on a website. I have found a code snippet that accomplishes this: //Scrolling of tweets in the footer $(function () { var tweetVP = $("#footerTweetsViewport"); arrTweetNav ...

Assigning properties in html

When the status is equal to "complete", I need to disable an input tag based on a certain condition. One way to achieve this using javascript is by utilizing the setAttribute method. var element = document.querySelector("input"); element.setAttribute("d ...

Locate the index and value of the item that has the most recent date

Exploring my API design const dataArr = [{ end_date: '2019-12-16' }, { end_date: '2018-12-16' }]; const latestEntry = dataArr.filter( /* Seeking the index of the item with the most recent date */ ); Interested in vanilla JavaScript ...

The Jquery tooltip feature consistently displays the title of the header as the tooltip

Currently, I am utilizing the default Jquery tooltip library, and it functions wonderfully with one exception. In Firefox, the tooltip always displays the title of the page (within <head>). For example: <title>My Title</title></head> ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

Struggling to align a div vertically using CSS is causing me some difficulties

Hey there, I'm trying to figure out how to align the "container2" div to the bottom of the "container," but I'm running into some issues. Can anyone lend a hand? HTML <div id="container"> <div id="container2"> ...