Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enlarge a clicked image with plain JavaScript on a mobile device

I'm trying to create thumbnail images that enlarge when clicked. The goal is to have the selected thumbnail enlarge itself to the maximum width of the device. If another thumbnail is clicked, its image will replace that of the currently selected thumbnail. Only one thumbnail can be enlarged at any one time.

The image should span the device's maximum width. Also, I am trying to accomplish this with plain JavaScript (no jQuery), CSS, and HTML.

JavaScript

function showImage(imgName) {
    document.getElementById('largeImg').src = imgName;
    showLargeImagePanel();
    unselectAll();
}
function showLargeImagePanel() {
    document.getElementById('largeImgPanel').style.visibility = 'visible';
}
function unselectAll() {
    if(document.selection) document.selection.empty();
    if(window.getSelection) window.getSelection().removeAllRanges();
}
function hideMe(obj) {
    obj.style.visibility = 'hidden';
}

HTML

<img  src="./Images/image.jpg" alt="1.jpeg" style="cursor:pointer" 
      onclick="showImage('./Images/image.jpg');">
<div id="largeImgPanel" onclick="hideMe(this);">
<img id="largeImg" style="height: 100%; margin: 0; padding: 0;">

CSS

#largeImgPanel {
    text-align: center;
    visibility: hidden;
    position: fixed;
    z-index: 100;
    top: 0; left: 0; 
    width:100%;
    height:100%; 
    background-color: rgba(100,100,100, 0.5);
}

The image does pop up, but it is too large (wider than that of the device), so it does't fit the mobile screen. How do I make it the right size?

like image 713
Blockspace21 Avatar asked Nov 10 '22 08:11

Blockspace21


1 Answers

You need to constrain the image width to the width of the parent container.

#largeImg  {
    height: auto;
    max-width: 100%;
}

This will force the image to be no bigger than the container it's held in, and automatically scale down on smaller screens.

like image 134
Axel Avatar answered Nov 14 '22 22:11

Axel