Magnifier

In this example below you will see how to do a Magnifier with some HTML / CSS and Javascript

Magnifier example for touch and mouse-based devices using css and background-image

Thumbnail
This awesome code was written by Kunuk Nykjær, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Kunuk Nykjær ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Magnifier</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<base href="//s3-us-west-2.amazonaws.com/s.cdpn.io/157670/">
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container bg-image">
  <div class="overlay"></div>
  <div class="img bg-image"> </div>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/kunukn/magnifier-YpadWZ */
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  height: 1px;
  min-height: 100vh;
  display: flex;
  background: #f6f6f6;
  background: rgba(0, 0, 0, 0.8);
}
body > * {
  margin: auto;
}

.container {
  position: relative;
  outline: 1px solid black;
  width: 1024px;
  height: 768px;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.8);
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.bg-image {
  background-image: url("nature-sunrise.jpg");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 1024px 768px;
  background-attachment: fixed;
}

.img {
  width: 200px;
  height: 200px;
  position: relative;
  display: block;
  cursor: pointer;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  -webkit-transform: scale(1.4);
          transform: scale(1.4);
}


/*Downloaded from https://www.codeseek.co/kunukn/magnifier-YpadWZ */
var width = 200,
    height = 200;

var log = console.log.bind(console);

var containerEl = document.querySelector('.container'),
    imgEl = containerEl.querySelector('.img');

function handleMove(event) {

  var eventToUse = event;

  if (event.type === 'touchstart' || event.type === 'touchmove') {
    eventToUse = event.changedTouches[0];
    event.preventDefault(); // prevent Y-scrolling when swiping up/down
  }

  var bcr = containerEl.getBoundingClientRect();
  var _eventToUse = eventToUse,
      clientX = _eventToUse.clientX,
      clientY = _eventToUse.clientY;

  var x = bcr.left,
      y = bcr.top;

  imgEl.style.left = clientX - x - width / 2 + 'px';
  imgEl.style.top = clientY - y - height / 2 + 'px';
}

containerEl.addEventListener('mousemove', handleMove);
containerEl.addEventListener("touchmove", handleMove, true);

Comments