Control elements that contain images with jQuery

If the element that contains your image has fixed dimensions; it takes up a space that equals the dimensions given, even when it’s empty. You wouldn’t want empty elements or spaces to ruin that gorgeous design after all the hard work you’ve put in, would you?. Luckily for you, there’s a super simple jQuery method that can help you find, target, style, or control elements that contain images.

Let’s learn how to Control elements that contain images with jQuery but before we continue, study the tutorial images below to understand why it’s important that we control elements that contain images.

Note

  1. Image #1 is present and it fits the given space. (No Problem)
  2. Image #2 is missing and the containing element still respects your commands (holds the given space) because no conditions were given. (Problem #1)
  3. Image #3 is present but doesn’t fit the given space because again no conditions were given (Problem #2)

From the above, we have 2 problem to solve so let’s starts solving them

  1. Hide the image container element when it’s empty

    The block of code below solves Problem #1 by checking if the supposed containing element has an image. It hides it if it finds it empty.

    $('.image-container').each(function() {   // For each image container  
    if ($(this).find('img').length === 0) {   // look for an image and if you don't find any  
    $(this).hide();     }    // Hide image container
    });
    
  2. Float the image when it doesn’t fit the given space

    The best way to solve Problem #2 would be to float the image left and let the text wrap around it if at any time the contained image doesn’t fit the container. That’s what the block of code below does.
    We added a filter that applies just to those image containers with small images.

    $('.image-container').each(function() { // For each image container
    if ($(this).find('img').length === 0) { // look for an image and if you don't find any
    $(this).hide(); } // Hide image container
        else {
             $(this).filter(function() { // Only those with a small image
            return $('img', this).filter(function() { // Check image width
               return $(this).width() < 300;  // Best to compare with image container width             
    }).length > 0;
                }).css({'float' : 'left', 'width' : 'auto', 'height' : 'auto', 'margin-right' : 20, 'margin-bottom' : 0});
    }
        });
    

 

Link to working and editable example
If you have problems implementing it, use the comment form below and I’d be glad to help you.

Leave a Reply