1

I'm trying to make a magnifying zoom on image on mouse hover. It should look like following the image. How could I do this without using any plugins?

enter image description here

1

1 Answer 1

1

Try this, it uses two different images, a small one and then a larger version of the same image for magnification.

$(document).ready(function(){
  var native_width = 0;
  var native_height = 0;
  $(".magnify").mousemove(function(e) {
    if(!native_width && !native_height) {
	  var image_object = new Image();
	  image_object.src = $(".small").attr("src");

	  native_width = image_object.width;
	  native_height = image_object.height;
    } else {
	  var magnify_offset = $(this).offset();
	  var mx = e.pageX - magnify_offset.left;
	  var my = e.pageY - magnify_offset.top;
			
	  if(mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
		$(".large").fadeIn(100);
	  } else {
		$(".large").fadeOut(100);
	  }
	  if($(".large").is(":visible")) {
		var rx = Math.round(mx/$(".small").width()*native_width - $(".large").width()/2)*-1;
		var ry = Math.round(my/$(".small").height()*native_height - $(".large").height()/2)*-1;
		var bgp = rx + "px " + ry + "px";
				
		var px = mx - $(".large").width()/2;
				var py = my - $(".large").height()/2;

		$(".large").css({left: px, top: py, backgroundPosition: bgp});
	  }
	}
  });
});
* {
  margin: 0; 
  padding: 0;
}

.magnify {
  width: 200px; 
  margin: 50px auto; 
  position: relative;
}

.large {
  width: 175px; height: 175px;
  position: absolute;
	
  box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 
	0 0 7px 7px rgba(0, 0, 0, 0.25), 
  inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
	
  background: url('http://thecodeplayer.com/uploads/media/iphone.jpg') no-repeat;
  display: none;
}

.small { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="magnify">
<div class="large"></div>
<img class="small" src="http://thecodeplayer.com/uploads/media/iphone.jpg" width="200"/>
</div>

Modified from: http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3

Sign up to request clarification or add additional context in comments.

2 Comments

it is helpful. But problem is that,when the image dynamically added in image url. How i replace the css image background url?
To change it with JQuery, $(".large").css("background-image", "url('whatever.png')"); or you could just change the css beforehand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.