show the full size image on mouse hover over follow the pointer in javascript

To show the full size image on mouse hover over in JavaScript, you can use the mouseover event and some basic HTML and CSS.

First, create an HTML <img> element with a thumbnail image. Then, add a CSS class to the image that sets its display to hidden and position to absolute.

<img src="thumbnail.jpg" class="thumbnail-image">
50 chars
2 lines
.thumbnail-image {
  display: none;
  position: absolute;
}
60 chars
5 lines

Next, add a JavaScript function that listens for the mouseover event on the image. In this function, you can create a new <img> element with the full size image and append it to the document body. Then, as the mouse moves, you can update the position of the new image to follow the mouse pointer.

index.tsx
const thumbnailImg = document.querySelector('.thumbnail-image');

thumbnailImg.addEventListener('mouseover', function() {
  const windowHeight = window.innerHeight;
  const imgSrc = this.getAttribute('src');

  const fullSizeImg = new Image();
  fullSizeImg.src = imgSrc.replace(/thumbnail/, 'full-size');
  fullSizeImg.style.position = 'absolute';
  fullSizeImg.style.top = 0;
  fullSizeImg.style.left = 0;
  fullSizeImg.style.display = 'block';
  fullSizeImg.style.maxHeight = `${windowHeight}px`;

  document.body.appendChild(fullSizeImg);

  document.addEventListener('mousemove', function(event) {
    fullSizeImg.style.top = `${event.clientY}px`;
    fullSizeImg.style.left = `${event.clientX}px`;
  });
});
714 chars
22 lines

In this JavaScript function, we:

  1. Get the height of the browser window
  2. Get the src attribute of the thumbnail image
  3. Create a new <img> element with the full size image
  4. Set the position of the new image to absolute and the display to block
  5. Append the new image to the document body
  6. Add a mousemove event listener that updates the position of the new image based on the mouse pointer

Note that in our example, we are assuming that the full size image has the same file name as the thumbnail image, except with the word "thumbnail" replaced with "full-size". You may need to adjust this to match your own naming scheme for images.

gistlibby LogSnag