Search code examples
javascriptjquerycssimagewindow-resize

resize div depending on an image size using jquery


I have an image and a colored div overlay over my image. I get the image width and height using jquery to set the colored overlay div width and heights. it works fine.

here is my html :

<div class="image_overlay">
    <div class="overlay"></div>
    <img src="http://us.123rf.com/400wm/400/400/1xpert/1xpert1101/1xpert110100083/8712640-rainbow-cubes-3d-render-image.jpg" class="image">
</div>

<div class="image_overlay">
    <div class="overlay"></div>
    <img src="http://4.bp.blogspot.com/-BrLngyC1Bto/UpO-IY1kcNI/AAAAAAAALqA/1bSQRy3G_gU/s1600/Image-b%C3%A9b%C3%A9-facebook-8.jpg" class="image">
</div>

my css

.image_overlay{
    position:relative}

.image{
    z-index:1;
    width:50%;
    height:auto;
}

.overlay{
    background-color:rgba(13, 181, 30, 0.8);
    position:absolute;
    z-index:2;
}

and my jquery

$(".image").load(function(){
    var image_h=this.height,
    image_w=this.width;
    $(".overlay").height(image_h);
    $(".overlay").width(image_w);
});

now I'm trying when resizing the window that the overlay get the same size of my image, using $(window).on('resize',function()... but I can't find out how to do it...

here is what I tried : http://jsfiddle.net/o4ngj624/

Can anybody help me with this ?

thanks a lot for your help,

$(document).ready(function(){

    $(".image").load(function(){
        var image_h=this.height,
        image_w=this.width;
        $(".overlay").height(image_h);
        $(".overlay").width(image_w);
    });

    $(window).trigger('resize');

});

$(window).on('resize',function() {

    var image_h=this.height,
    image_w=this.width;
    $(".overlay").height(image_h);
    $(".overlay").width(image_w);
});

here is Jsfiddle to see it in action :


Solution

  • You should just trigger load event of image.

    $(document).ready(function () {
        $(".image").load(function () {
            var image_h = this.height,
                image_w = this.width;
            //Use prev to find previous overlay
            $(this).prev(".overlay").height(image_h).width(image_w);
        });
    });
    
    $(window).on('resize', function () {
        $(".image").trigger('load'); //Trigger load event of image
    }).trigger('resize');
    

    DEMO