Buddhi Dananjaya Buddhi Dananjaya - 5 months ago 11
CSS Question

Image resizing issue on Html

I tried following. It works on fiddle. But not work with html. Imgae get loaded but not resizing it while hoovering.



<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var current_h = $('img').height();
var current_w = $('img').width();

$('.resize').hover(
function () {
$(this).stop(true, false).animate({
width: (current_w * 3.15),
height: (current_h * 3.15)
}, 300);
}, function () {
$(this).stop(true, false).animate({
width: current_w + 'px',
height: current_h + 'px'
}, 300);
});
</script>
</head>
<body>
<div class="box">
<img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/>
</div>
</body>
</html>





Any issue in here ?

Answer

You need to execute onload - your code is run before the image exists:

$(function() { // when the page has loaded
  var current_h = $('img').height();
  var current_w = $('img').width();

  $('.resize').hover(
    function() {
      $(this).stop(true, false).animate({
        width: (current_w * 3.15),
        height: (current_h * 3.15)
      }, 300);
    }, function() {
      $(this).stop(true, false).animate({
        width: current_w + 'px',
        height: current_h + 'px'
      }, 300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="box">
  <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" />
</div>

If you have more than one image, you can save each image size in the img's data attribute - I also added the height to the image tag.

$(function() { // when the page has loaded
  $(".box img").each(function() {
    $(this).data("w",$(this).width());
    $(this).data("h",$(this).height());
  });
  $('.resize').hover(
    function() {
      $(this).stop(true, false).animate({
        width: ($(this).data("w") * 3.15),
        height: ($(this).data("h") * 3.15)
      }, 300);
    }, function() {
      $(this).stop(true, false).animate({
        width: $(this).data("w") + 'px',
        height: $(this).data("h") + 'px'
      }, 300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="box">
  <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" height="250" />
</div><div class="box">
  <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" height="250" />
</div>