Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript jQuery Get Image Dimensions, Apply To Div

  • This topic is empty.
Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #154889
    Steven Morgan
    Participant

    I want a div to get an inline style of the image it wraps around.

    Pen here: http://codepen.io/stevenmorgan94/pen/xuEwm

    So jquery get image dimensions, add inline style to .box with the width and height

    #154891
    Paulie_D
    Member

    You can do this will CSS.

    Just set the div to display:inline-block.

    http://codepen.io/Paulie-D/pen/Dgzqm

    #154893
    Steven Morgan
    Participant

    Thanks Paul, I know that. My reasoning for doing it dynamically is I have clients adding photos of different sizes into a box. So I need jQuery to determine that size and apply it to the div that wraps the image.

    #154894
    Steven Morgan
    Participant

    And the box has to have exactly dimensions because of the jQuery plugin I’m using that centers it on the page.

    #154896
    Steven Morgan
    Participant

    Ah I figured it out

    var img = $(".box > img");
    $(".box").css({width:img.width(), height:img.height()});
    
    #154898
    Josh
    Participant

    Hiya Steven. The solution you posted won’t work if there are multiple .box elements on the page containing different-sized images.

    You want something more like this:

      // For each .box element
      $('.box').each(function() {
        // Set up the variables
        var $this = $(this),
            w = $this.find('img').width(), // Width of the image inside .box
            h = $this.find('img').height(); // Height of the image inside .box
        $this.width(w).height(h); // Set width and height of .box to match image
      });
    

    http://codepen.io/JoshBlackwood/pen/kLDoI

    Edited to add: If you’re only going to have one .box on a given page, then your solution will be fine. Mine is simply more futureproof and flexible, at the cost of a few more lines of code.

    #154905
    Steven Morgan
    Participant

    Perfect, thanks man.

    #154924
    Josh
    Participant

    No problem, glad to help!

Viewing 8 posts - 1 through 8 (of 8 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.