Home > OS >  resize image in jquery don't applied
resize image in jquery don't applied

Time:12-25

i want to resize some images when page load.i wrote this codes: but some times applied but sometimes don't applied. any ideas??

$(document).ready(function () {
$( ".img-product" ).each(function( index ) {
        let h=$( this ).height();
        let w=$( this ).width();
        //console.log( index   ": "   w   ":"  h   ":"   $(this).attr('alt'));
        if( h>= 300)
        {
            $(this).removeClass("w-100");
            //console.log( index   ": "   w   ":"  h   ":"   $(this).attr('alt'));
            $(this).css({
                   'width' : 'auto',
                   'margin-right':'auto',
                   'margin-left':'auto'});
                   
                   
        }
         
});
})

CodePudding user response:

You can use a load event directly on the images, so the callback will execute on an image when it's loaded.

$(document).ready(function () {
    $(".img-product").on("load", function() {
        let h=$(this).height();
        let w=$(this).width();
        //console.log( w   ":"  h   ":"   $(this).attr('alt'));
        if(h >= 300)
        {
            $(this).removeClass("w-100");
            //console.log( w   ":"  h   ":"   $(this).attr('alt'));
            $(this).css({
                   'width' : 'auto',
                   'margin-right':'auto',
                   'margin-left':'auto'});
                   
                   
        }
    });
})

CodePudding user response:

Use this:

$(window).on('load', function() {
 // code here
});

instead of

$(document).ready(function () {
//code
}
  • Related