What are some creative ways to utilize Zoom for displaying a collection of images?

Anyone know how to create a zoom gallery using classes instead of ids? I found this code which is short, but it doesn't work with classes.

Check out the code here

I need help figuring out how to modify this code to work with classes for building my gallery. Any suggestions?

Answer №1

You have the option to implement dynamic IDs for this task. I have devised a snippet that features 4 distinct images with varying IDs, and the zoom effect functions seamlessly.

I find it more convenient to approach it in this manner rather than modifying the zooming functionality for classes.

// presenting an array of images
// each with RANDOM IDs!
const images = [{
    id: Date.now() - 400,
    src: 'https://loremflickr.com/1200/960/girl/all?random=1'
  },
  {
    id: Date.now() - 200,
    src: 'https://loremflickr.com/1200/960/girl/all?random=2'
  },
  {
    id: Date.now() + 200,
    src: 'https://loremflickr.com/1200/960/girl/all?random=3'
  },
  {
    id: Date.now() + 400,
    src: 'https://loremflickr.com/1200/960/girl/all?random=4'
  },
];

// displaying the images dynamically
(function(images) {

  let html = ''
  images.forEach(image => {
    html += `
      <h2>ID: ${ image.id }</h2>
      <div class="img-zoom-container d-flex">
        <img id="${ image.id }" src="${image.src}" width="300" height="240" alt="Girl">
        <div id="${ image.id }-result" class="img-zoom-result"></div>
      </div>
      <hr />
    `
  })
  const container = document.getElementById('container')
  container.innerHTML = html

  const imagelist = document.querySelectorAll('.img-zoom-container > img')

  // adding event listener for the random IDs
  imagelist.forEach(image => {
    image.addEventListener('mouseenter', function(e) {
      imageZoom(e.target.id, `${ e.target.id }-result`)
    })
  })

})(images);


// code courtesy of W3 Schools
// https://www.w3schools.com/howto/howto_js_image_zoom.asp
function imageZoom(imgID, resultID) {
  var img, lens, result, cx, cy;
  img = document.getElementById(imgID);
  result = document.getElementById(resultID);
  /* Create lens: */
  lens = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /* Insert lens: */
  img.parentElement.insertBefore(lens, img);
  /* Calculate the ratio between result DIV and lens: */
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  /* Set background properties for the result DIV */
  result.style.backgroundImage = "url('" + img.src + "')";
  result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
  /* Execute a function when someone moves the cursor over the image, or the lens: */
  lens.addEventListener("mousemove", moveLens);
  img.addEventListener("mousemove", moveLens);
  /* For touch screens as well: */
  lens.addEventListener("touchmove", moveLens);
  img.addEventListener("touchmove", moveLens);

  function moveLens(e) {
    var pos, x, y;
    /* Prevent any other actions that may occur when moving over the image */
    e.preventDefault();
    /* Get the cursor's x and y positions: */
    pos = getCursorPos(e);
    /* Calculate the position of the lens: */
    x = pos.x - (lens.offsetWidth / 2);
    y = pos.y - (lens.offsetHeight / 2);
    /* Ensure the lens stays within the boundaries of the image: */
    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;
    }
    /* Position the lens accordingly: */
    lens.style.left = x + "px";
    lens.style.top = y + "px";
    /* Show what the lens "sees": */
    result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
  }

  function getCursorPos(e) {
    var a, x = 0,
      y = 0;
    e = e || window.event;
    /* Find the x and y positions of the image: */
    a = img.getBoundingClientRect();
    /* Calculate the cursor's x and y coordinates relative to the image: */
    x = e.pageX - a.left;
    y = e.pageY - a.top;
    /* Consider any page scrolling: */
    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {
      x: x,
      y: y
    };
  }
}
* {
  box-sizing: border-box;
}

.d-flex {
  display: flex;
}

.img-zoom-container {
  position: relative;
}

.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /* Set dimensions for the lens: */
  width: 40px;
  height: 40px;
}

.img-zoom-result {
  border: 1px solid #d4d4d4;
  /* Set size for the result div: */
  width: 300px;
  height: 300px;
}
<div id="container"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In PHP, a boolean variable will not display on the webpage when echoed

I am facing an issue with my PHP code where certain variables are not being echoed properly in the generated JavaScript. The code is designed to check if specific values are assigned in the $_GET global array and assign default values if they are not prese ...

Upgrade to Bootstrap 5 - Implement Video Modal Feature

I need to update a modal with a video inside from Bootstrap 4 to Bootstrap 5 without jQuery. The issue lies in the JavaScript code below: <script> // codepen.io/JacobLett/pen/xqpEYE $(document).ready(function() { var $videoSrc; $(&a ...

Which option offers better performance in Three.js: utilizing a sprite or a BufferedGeometry?

I am currently in the process of revamping an outdated visualization created a few years back using an earlier version of Three.js. The visualization consists of approximately 20,000 2D circles (nodes from a graph) displayed on a screen with predetermined ...

Unable to initiate any actions with vue-select

Currently, I'm utilizing vue-select to input or select from a dropdown. Upon selecting an option, my goal is to retrieve the value that has been selected. Sample Code <vueSelect :clearable="false" v-on:change="itemCodeChange($event ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Chrome 83 is flagging required properties as undefined

After updating to chrome version 83, I encountered a problem where one of the pages in my app crashes. It seems that some required props are undefined. This issue only occurs in Chrome; when I tested it on IE 11, Edge, and Firefox, it worked perfectly fi ...

The power of selenium meets the functionality of Javascript with the webdriver

Encountering an issue with Selenium JS Components are created in JSON format as follows: "usernameInputField": { "selector": { "xpath": "//*[@id='username']" } } For invoking webdriver, the following is used: var webdriver = ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

What could be causing this JS/jQuery to affect numerous inputs at once?

Everything is working smoothly with the code in the 'phone' input field. It formats the phone number correctly as the user types. However, there seems to be an issue with the event listener being added to another input named 'twofactor' ...

Smartlook fails to correctly store user consent

I am currently working on integrating Smartlook into our website. Since we are using React, I am unable to follow the suggested steps in the documentation which can be found here. Our implementation involves initializing Smartlook using a script tag in th ...

JavaScript generates a series of checkboxes dynamically, all lined up in a single row

I am currently working on a script where I iterate over objects and aim to display the text of each object on a new line in the list format, along with a checkbox next to it. Despite successfully printing everything with a checkbox, the issue I am facing i ...

The functionality of .attachClickHandler() is not maintained when the page is refreshed or redirected

I've encountered an issue while trying to integrate a custom Google login button in my index.html file. Initially, everything functioned flawlessly upon page load, with console outputs 1, 2, and 3 appearing sequentially, followed by output 4 upon sign ...

Exploring the Process of Iterating Through a JSON Array in Angular

Within my angular application, I am utilizing an API to retrieve data regarding a chosen country. However, I am encountering difficulties in showcasing the "name" property from the languages section within the response data: [{ "name": "Colombia", ...

Sorting Tables through the Power of Drag and Drop

While utilizing both the Jquery Tablesorter plugin and the Drag and Drop plugin together, everything seems to be functioning correctly. However, when attempting to use the serialize function of the tableDnD, an error message stating "empty string getElemen ...

What exactly entails static site generation?

I have been exploring the concept of static site generation (SSG). The interesting question that arises is how SSG can fetch data at build time. In my latest application, I implemented an event handler to retrieve data based on a user's search keyword ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Managing State in React: A Guide to Updating Child Component State from Parent Component

I'm still fairly new to working with React and I'm trying to implement a Bootstrap modal for displaying alert messages. Within my main App.js file, I have an error handler that sends a prop to a Modal.js component in order to trigger the modal t ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...