Nathan_Sharktek
Nathan_Sharktek

Reputation: 407

jQuery / JS wait until image width adjusted

I am having an issue with timing during the loading functions of my page. The issue that I need to get the width of an image after it has been

(1) Loaded

(2) 100% Width adjusted by CSS

The image width is set to 100% and adjusts about 300ms after the my AJAX POST is returned but I don't want to use a timeout at the load time may differ.

    parsed_return.forEach(function(entry) {
        entry.pages.forEach(function(page) {
            $('<div style="margin-bottom: 50px;">' + 
                '<div class="col-xs-1"></div>' + 
                '<div class="col-xs-10 page" id="' + page.id + '" style="padding: 0px;">' + 
                    '<img class="image" src="' + base_url + page.page_uri + '&dpi=150">' +
                '</div>' + 
                '<div class="col-xs-1"></div>' + 
            '</div>').data( 'page_id', page.id ).addClass( 'row' ).appendTo( '#page-view' );
            page_list.push(page.id);

            console.log($("#" + page.id + " img").width()); // Outputs 1279px (Natural)
        });
    });

    setTimeout(function(){
        console.log($("#page-view .page img").first().width()); // Outputs 1279px (Natural)
    },100);

    setTimeout(function(){
        console.log($("#page-view .page img").first().width()); // Outputs 1267px (adjusted to 100% based on window size)
    },300);

I need to get the width of the image AFTER it has been adjust to 100% of the parent element (based off window size) and not run the next AJAX POST until then. Is there anyway for me to do this properly?

Thank you for looking!

Upvotes: 0

Views: 148

Answers (3)

SANBI samples
SANBI samples

Reputation: 2118

Here's an example of code you can include in your css file to make adjustments to your image before media queries are executed:

body::before {
opacity:0.3;
background: url(/images/DNA.jpg) no-repeat center center fixed;
content: '';
z-index: -1;
width: 100%;
height: 100%;
position:absolute; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}

Upvotes: 0

I realy recommend you using the jquery.waitForImage it does all the loading images for you, and after the loading you can play as you want with them.

Upvotes: 2

ahervin
ahervin

Reputation: 461

if($("#page-view .page img").first().width() == $("#page-view .page img").first().parent().width()) 

You could make a function that checks using above logic when the Image matches the parent width

Upvotes: 0

Related Questions