Olli Olli - 7 months ago 16
Javascript Question

Enlarge images in my html page using JavaScript

I try to enlarge images in my html page by using JavaScript.
The image in the html- source code always has the height/width 100 Pixel. By clicking on the image, the image should be displayed in original size.
By clicking the image again, the image should displayed in height/width 100 Pixel.

Example image in the html source code:

<img src="image.jpg" onClick="swap(this)" onmouseover="" style="cursor: pointer;" height="100" width="100">


My JavaScript source code:

function swap(img)
{
if (img.width==="100")
{
img.width="auto";
img.height="100%";
}
else
{
img.width="100";
img.height="100";
}
}


My Problem is the image size dose not change. What am I doing wrong?
Does anyone have maybe a better idea?

Answer

Provided your images don't already have a CSS class, you can swap a full-size class easily.

function swap(img) {
  if (img.className !== "full-size") img.className = "full-size";
  else img.className = "";
}
.full-size {
  height: 100%;
  width: 100%;
}
<img src="https://multimedia.journalism.berkeley.edu/wp-content/uploads/2014/09/css101-main.jpg" onClick="swap(this)" onmouseover="" style="cursor: pointer;" height="100" width="100">

You'd be better off using jQuery to handle multiple classes on a single HTML element though.

Comments