22

I've looked for this everywhere for weeks, and I simply cannot find something to tell me what I'm doing wrong or how to even proceed. The goal is to create a function similar to Amazon's zoom in on mouseover for products with small images.

I'm currently at a loss for how to proceed, though I am aware that I will require two images- one in the "zoomed in" size and one in the "zoomed out" size. I'm not using Jquery- I cannot install it or any plugins to the website via my employer's request. I'm basically asking for the harder answer, and I apologize for that in advance. I must do this from moderate scratch. Warning: I am a programming Student. Take that as you will.

I've got HTML and CSS script, and because we don't actually have an IDE here I'm doing this on codecademy's project section, otherwise I'd have to program this completely live. You can find my code here, but I'll also post the code below, as that link is bound to have changing code since it uses procedural saving.

Note: I originally had it so that the gray box was following my mouse at relative center. It was flickering as it moved, but it was working. Currently though it's decided not to, at least on my work computer. I've not tested it on my personal computer.

Edit: The code is working on my Surface Pro 3, though it does follow the mouse off of the image (which is temporary and something random I grabbed). I'm not sure why the code isn't working on my work computer, though it's probable because it's a Macintosh OSX version 10.6.8...

HTML Code:

<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='style.css'/>
    <script src='script.js'></script>
</head>
<body>

<img id="imgZoom" onmousemove="zoomIn()" onmouseout="zoomOut()" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg">
<div id="overlay" onmousemove="zoomIn()"></div>
</body>
</html>

CSS Code:

#imgZoom {
    height: 300;
}

#overlay {
    visibility: hidden;
    position: absolute;
    left: 0px;
    top: 0px;
    width:20%;
    height:20%;
    padding: 25px;
    border: 5px solid gray;
    background-color: white;
    opacity:0.4;
    text-align:center;
    z-index: 1000;
}

Javascript code:

function zoomIn()
{
    var element = document.getElementById("overlay");
    element.style.visibility = "visible";

    var x = event.clientX;     // Get the horizontal coordinate
    var y = event.clientY;     // Get the vertical coordinate

    element.style.top = y - 80;
    element.style.left = x - 80;
}

function zoomOut()
{
    var element = document.getElementById("overlay");
    element.style.visibility = "hidden";
}
Kitfoxpup
  • 265
  • 1
  • 2
  • 11
  • jQuery doesn't require installation its just like uploading or Adding files on web server or if you cannot do that insert script tag with src from jQuery CDN or its website `` – CY5 Nov 19 '15 at 18:05
  • @CY5 Sorry about that, I figured JQuery required some installation, especially if you want to use things like Bootstrap. Where I attend school for programming, most of my instructors have warned us not to rely on JQuery, as it's more a crutch than a surefire answer- not that JQuery's a bad thing, it's just as a student I'm trying to learn the full method. I suppose that's mainly the reason I don't want to use it, so that I can learn how to do it manually. I'm actually mainly a programmer for video games, so ridiculously difficult code that has no helpers is usually what I do all day – Kitfoxpup Nov 19 '15 at 18:37
  • I agree with you since you are learning you have right to know how things are made from there core but in future remember reinventing the wheel is bad where you work in time constraint if you can do it easily with some tool, becoz you don't know when your things will break – CY5 Nov 19 '15 at 18:46
  • @CY5 oh absolutely, I don't disagree. They warn us against that too. Fortunately my employer is interested in seeing it working on its own as well- this is more an entry level position, and very lax on how things are done, so I'm taking my time to smooth out the work. Later on, of course, once I have a full understanding, I'll make use of faster methods! Speed is always key in any industry – Kitfoxpup Nov 19 '15 at 19:33

4 Answers4

41

you can just do it by playing background-position on mouse-over just moving background-position on mouseover DEMO

function zoomIn(event) {
  var element = document.getElementById("overlay");
  element.style.display = "inline-block";
  var img = document.getElementById("imgZoom");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition = (-posX * 4) + "px " + (-posY * 4) + "px";

}

function zoomOut() {
  var element = document.getElementById("overlay");
  element.style.display = "none";
}
#overlay {
  border: 1px solid black;
  width: 200px;
  height: 200px;
  display: inline-block;
  background-image: url('https://via.placeholder.com/400.png');
  background-repeat: no-repeat;
}
<img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="https://via.placeholder.com/200.png">
<div id="overlay" onmousemove="zoomIn(event)"></div>
glinda93
  • 7,659
  • 5
  • 40
  • 78
CY5
  • 1,551
  • 17
  • 23
  • This looks fantastic, I'll try giving this a run too. Both options I've received so far are fantastic! – Kitfoxpup Nov 19 '15 at 19:22
  • I tried your code @CY5, but i am getting a square at the bottom of the image and the zoomed image is static and showing the top right part of actual image. – Rahul Sharma Aug 10 '17 at 03:42
  • This works great for me. Why buy some online tool when there is such a simple solution as this? Thank you. – Ryan Walker Apr 20 '18 at 20:11
  • 1
    Guys, if your zoomed image center position does not correspond to where you have the mouse cursor, then you have to substitute the ```'4' in (-posX * 4) + "px " + (-posY * 4) + "px";``` with other numbers that work for you. In my case, for example, those where 0.5 and 0.8. – Javi Marzán Sep 01 '20 at 15:12
  • Also, if you need to modify the zoom of the image, you can do so adding ```background-size: 250%;``` to the ```overlay``` css.The bigger the percentage, the bigger the zoom. – Javi Marzán Sep 01 '20 at 15:13
8

This works for me: (Here is a JSFiddle)

#imgZoom {
    height: 300;
}
img#imgZoom:hover {
    position: relative;
    -webkit-transform: scale(1.5);
    -ms-transform: scale(1.5);
    -o-transform: scale(1.5);
    transform: scale(1.5);
    z-index: 1000;
}

You can also add this for a cool transition effect:

* {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

*Also, you can apply the same logic not only for images, but for divs as well.

Amit
  • 5,924
  • 7
  • 46
  • 94
1

function zoomIn(event) {
  var element = document.getElementById("overlay");
  element.style.display = "inline-block";
  var img = document.getElementById("imgZoom");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition = (-posX * 4) + "px " + (-posY * 4) + "px";

}

function zoomOut() {
  var element = document.getElementById("overlay");
  element.style.display = "none";
}
#overlay {
  border: 1px solid black;
  width: 100px;
  height: 100px;
  display: inline-block;
  background-image: url('http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg');
  background-repeat: no-repeat;
}
<img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg">
<div id="overlay" onmousemove="zoomIn(event)"></div>
0

try this

window.addEventListener("load", imageZoom("my-image"));

function imageZoom(imgID) {
    let img, lens, result, cx, cy;
    img = document.getElementById(imgID);
    result = document.getElementById("my-result");
    lens = document.querySelector(".img-zoom-lens");
    cx = result.offsetWidth / lens.offsetWidth;
    cy = result.offsetHeight / lens.offsetHeight;
    result.style.backgroundImage = "url('" + img.src + "')";
    result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
    lens.addEventListener("mousemove", moveLens);
    img.addEventListener("mousemove", moveLens);
    lens.addEventListener("touchmove", moveLens);
    img.addEventListener("touchmove", moveLens);
    function moveLens(e) {
        let pos, x, y;
        e.preventDefault();
        pos = getCursorPos(e);
        x = pos.x - (lens.offsetWidth / 2);
        y = pos.y - (lens.offsetHeight / 2);
        if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
        if (x < 0) {x = 0;}
        if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
        if (y < 0) {y = 0;}
        lens.style.left = x + "px";
        lens.style.top = y + "px";
        result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
    }
    function getCursorPos(e) {
        let a, x = 0, y = 0;
        e = e || window.event;
        a = img.getBoundingClientRect();
        x = e.pageX - a.left;
        y = e.pageY - a.top;
        x = x - window.pageXOffset;
        y = y - window.pageYOffset;
        return {x : x, y : y};
    }
}

// Function to change Images
(function () {
  let originalImg = document.querySelector("#my-image");
  let galleryImg = document.querySelector(".img-gallery").children;

  for(let i = 0; i < galleryImg.length; i++) {
    galleryImg[i].onclick = function() {
      originalImg.setAttribute("src", this.getAttribute("src"));
      imageZoom("my-image");
    };
  }
})();
* {
  box-sizing: border-box;
  font-family: sans-serif;
}

.img-container {
  position: relative;
  display: flex;
  justify-content: space-between;
}

.img-zoom-lens {
  position: absolute;
  border: 3px solid rgb(0, 126, 255);
  background-color: rgba(0, 126, 255, .2);
  width: 40px;
  height: 40px;
}

#my-image {
  max-width: 50%;
  height: 300px;
}

.img-zoom-result {
  border: 1px solid #f1f1f1;
  width: 300px;
  height: 300px;
}

.img-gallery {
  margin: 16px 0;
}

.img-gallery img {
  display: inline-block;
  cursor: pointer;
  width: 110px;
  height: 110px;
  border: 1px solid #ccc;
  padding: 4px;
  margin-right: 8px;
}

.img-gallery img:active {
  box-shadow: 0 0 0.1rem 0.1rem rgba(38,143,255,.5);
}

.img-gallery img:focus {
  box-shadow: 0 0 0.1rem 0.1rem rgba(38,143,255,.5);
}
<h1>Create an Image Zoom</h1>

<div class="img-container">
  <div class="img-zoom-lens"></div>
  <img id="my-image" src="https://parrot-tutorial.com/images/carousel_red3.jpg">
  <div id="my-result" class="img-zoom-result"></div>
</div>

<p>Choose more images:</p>
<div class="img-gallery">
    <img src="https://parrot-tutorial.com/images/avatar.jpg">
    <img src="https://parrot-tutorial.com/images/bottleship.jpg">
    <img src="https://parrot-tutorial.com/images/toxic.jpg">
</div>

Reference:Create an Image Zoom

Vishal
  • 268
  • 4
  • 3