How can I incorporate CSS to expand my image on click? HTML, CSS, JAVASCRIPT

https://www.w3schools.com/howto/howto_css_modal_images.asp

I want to do something like this:

So whenever I click, it enlarges the image.

Instead of doing it with a single I want to do it with:

<div style="background-color: #31363f;"class="w3-container w3-card-4 w3-center">
  <br>
<div id="img"></div>
  <br>
  <br>
</div>

<script>
const twinimgLimit = 145;
const twinimgNumber = Math.floor(Math.random() * twinimgLimit);
var twinurl = "https://media.publit.io/file/Twintails/" + twinimgNumber + ".jpg"
document.getElementById("img").innerHTML = `<img src=${twinurl} alt="neko" class="w3-image w3-card-4" onclick="document.getElementById('modal01').style.display='block'">`
</script>

Thanks!

2 Likes

Hi!

I’m not totally sure what you’re going for here but I thought I’d chip in with a method of enlarging an image on-click with CSS only bc I think it’s neat:

HTML

<div>
  <button class="imgLink">
	<img
	  src="https://cdn.glitch.com/cb562394-de5e-45a2-a7c3-8f9f92dfcd96%2Flarge_57c96640fd8e6c5e5858158c07db0205.jpg?v=1598517670675"
	  alt="artificial lake"
	/>
  </button>

  <button class="imgLink">
	<img
	  src="https://cdn.glitch.com/cb562394-de5e-45a2-a7c3-8f9f92dfcd96%2Fa0640277725_5.jpg?v=1598518242592"
	  alt="album art"
	/>
  </button>
</div>

CSS

.imgLink { border: none; background: none; }
.imgLink img
{
  height: 8rem;
}
.imgLink:active img, .imgLink:focus img
{
  height: 16rem;
}

We put each image in an invisible button. When the button containing an image is “focussed”, (i.e it’s the last thing the user clicked) we increase the height. If the user clicks the page background or another button, it goes back to normal.

Demo Glitch: glitch.com/~bevel-funky-orca

I’m suggesting you a way to do so, not the actual code.

You can cover the whole webpage with a .overlay div, when clicked on the image, and pass the image in it, then display: block it.
Make the image take full width / height, by max-height or max-width css property.

And, when the div is clicked (note that, initially the image was clicked, and div was display: none), hide the div again, and thus enlarged image will disappear.

Pretty cool! OP used inline functions again in HTML - kind of a pet peeve for me haha. Where can I find all the images hosted on Glitch’s CDN?

3 Likes

They’re hidden behind a GUID for each project, so you can only really find the assets for your projects.

Btw nothing wrong with a little bit of inline JS if it’s only a little bit :wink: Reduces number of requests and download time… I use a little bit on https://stegriff.co.uk/

1 Like

I see, so those are assets for your project.

Early on when I was learning to code I once wrote 50 characters for an inline function… :sweat_smile:not my proudest moment.

2 Likes