Search code examples
jqueryscale

Calculate the width and height of parent div and apply to image accordingly


I have a parent div which in responsive width and fixed height with some images inside it. On runtime I need a Jquery function to calculate the width and height of the div and apply the width (px) and height (px) parameters to image. i.e my code right now is

<div id="slider-wrapper" class="someclass">
    <img src="/image1.jpg" alt="" />
    <img src="/image2.jpg" alt="" />
    <img src="/image3.jpg" alt="" />
</div>

the generated code which I need would be

  <div id="slider-wrapper" class="someclass">
    <img src="/image1.jpg" height="300px" width="total-div-width(px)" alt="" />
    <img src="/image2.jpg" height="300px" width="total-div-width(px)" alt="" />
    <img src="/image3.jpg" height="300px" width="total-div-width(px)" alt="" />
</div>

Thank you in anticipation


Solution

  • Using jQuery you can use .height(), .innerHeight() or .outerHeight().

    The differences are:

    • height() returns just the height of the element, no borders, no margins and no padding
    • innerHeight() returns the element height and the padding
    • outerHeight() returns the element height, the padding and borders
    • outerHeight(true) returns the element height, the padding, borders and margins

    I have more details including output examples using jsFiddle in this post here.

    For width you can use width(), innerWidth() or outerWidth().
    The same logic applies as with height.

    All values are in pixels.

    To get the height/width you can use it similar to this:

    // The below is an example, you need to add your element references as required.
    
    // Use height(), innerHeight() or outerHeight() as needed.
    var newHeight = $("#slider-wrapper").height();
    
    // Use width(), innerWidth() or outerWidth() as needed.
    var newWidth = $("#slider-wrapper").width();
    

    To set the height/width you can use it similar to:

    // The below is an example, you need to add your element references as required.
    var newHeight = $("#slider-wrapper img").height(newHeight);
    var newWidth = $("#slider-wrapper img").width(newWidth);