skip to Main Content

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'});
                   
                   
        }
         
});
})

2

Answers


  1. Use this:

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

    instead of

    $(document).ready(function () {
    //code
    }
    
    Login or Signup to reply.
  2. 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'});
                       
                       
            }
        });
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search