April 5, 2012

auto fit image in div / jquery

Question by tintincutes

How can I auto-fit an image if my code is like this:

<script type="text/javascript"> 
jQuery.noConflict();
jQuery(document).ready(function () {
    var count = 0;
    function animate() {
        jQuery(".fadein").eq(count).fadeIn(1000);
        count++;
        if(count <= jQuery(".fadein").length) {
            setTimeout(animate, 1000);
        } else {
            jQuery("a.fadein").fadeOut(1000);
            count = 0;
            animate();
        }      
    }
    animate();
});
</script>

Would this be correct?

<script type="text/javascript"> 
    jQuery.noConflict();
    jQuery(document).ready(function () {
        var count = 0;
        function animate() {
            jQuery(".fadein").eq(count).fadeIn(1000);
            count++;
            if(count <= jQuery(".fadein").length) {
                setTimeout(animate, 1000);
            } else {
                jQuery("a.fadein").fadeOut(1000);
                count = 0;
                animate();
            }      
        }
        animate();
    })
            function fitImagetoContainer() {   $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic   
       }); }

//Call the function at load 
      $(window).load(function() {    fitImagetoContainer(); });


//Also call the function when the window resizes  
      $(window).resize(function() {    fitImagetoContainer(); });;
    </script>

Answer by Starx

Here is my throw at your problem

//Create a function to resize the image with respect to parent
function fitImagetoContainer() {
  $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic
  });
}

//Call the function at load
$(window).load(function() {
   fitImagetoContainer();
});


//Also call the function when the window resizes 
$(window).resize(function() {
   fitImagetoContainer();
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!