16 Mayıs 2013 Perşembe

Adding images dynamically via jQuery and resizing according to the container

Hi, suppose that you have a web service which returns image url's and you need to load them dynamically into your page via javascript with the help of jQuery but image sizes can vary and you need to resize them according to the size of your container div but if the image is smaller than the container div then you need to leave them as they are. You tried to set img tags display style as inline but it didn't work. Then you are welcome here is the solution for this trouble:
HTML

<div id="containerDivId" width="580" height="380" />
                        


Script

var img = $('<img>'); 
img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Rubber_duck.jpeg/512px-Rubber_duck.jpeg');
img.appendTo('#containerDivId');

if(img[0].width>580)
   img[0].width = 580;
if(img[0].height>380)
  img[0].height = 380;