Need help from someone who understands JS

So, I’m in a solo Hackathon. And I need to display images at the full viewport size which, which clicked, become the next picture. There’s four pictures in total and then it turns into the game. I made it like that because making four cut scenes in HTML and CSS would have ended me. So, is this possible?

I made divs in HTML before the game then I added the images into CSS. I’ve been messing around with JavaScript, I don’t get how to make it so though one image shows, then when it’s clicked, it disappears and is replaced by the second and so on and then the game starts.

Please help me, I’ve been awake for 36 hours!

do you have this live somewhere, such as in “repl/codesandbox/etc”?

  • sleep is very important, and its highly recommended, go get some if you havent already

happy coding :slight_smile:

2 Likes

Please sleep

If you put this question into chatgpt it could probably give you the answer a lot quicker than this forum can

Assuming you have something like

<figure id="imagecontainer">
  <img />
  <img />
  <img />
  <img />
</figure>

Get an array of the image elements (like images = Array.from(imagecontainer.querySelectorAll("img"))

Add an active class to the first image (like images[0].class list.add("active"))

Store the currently active index in a variable (like currentImageIndex = 0)

Add an event handler listening for click events (like imagecontainer.addEventListener("click", (event) => { /* logic here */)

On click, if you aren’t on the final image, remove the active from the currently active index and add it to the image at the currently active index + 1 (like images[currentImageIndex].classList.remove(active), then images[currentImageIndex + 1].class list.add("active"))

Update the currently active index variable.

If the currently active index is the same as the last index (ie you’re on the last image and click once more), then do whatever it is you want to do next


This is rough. But it’ll work perfectly well. I’d probably use a class here to encapsulate the logic, or go slightly further & make it a web component

Please sleep! Brains require sleep.

1 Like

It seems easier to put the images in an array and index into the array.

Index into the array, if you get back an image set the source and increment the index, if you do not get back an image you have reached the end of the array and can start the game.

array of images
image element
index

click handler
  get image from array using index
  if image
    set image
	increment index
  else
    start game

you have over stressed it, take a nap and then focus.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.