A spookily simple web app game

1 minute read

Originally published on: https://dev.to/ibmdeveloper/spooky-byte-sized-tech-tips-round-up-week-4-56an

I recently made a spooky little project in about an hour for my son. It’s just some HTML and Javascript. Calling it a “Web App” would be pushing it. There’s nothing fancy as I wanted it to be served on GitHub Pages. Just click on a button to set the image source and visibility. Bootstrap was used so I could just pull in a decent looking theme easily.

Try it out below

Or watch the GIF

Trick or Treat GIF

Let’s look at the code

One thing worth noting is that I learned how to make webpages that use Bootstrap more mobile friendly by adding this line to the header.

<meta name="viewport" content="width=device-width, initial-scale=1">

HTML body

<nav class="navbar navbar-default">
  <div class="container-fluid">
      <div class="navbar-header">
          <a class="navbar-brand" href="https://github.com/stevemar/trick-or-treat">GitHub Repo</a>
      </div>
  </div>
</nav>

<div class="container-fluid">

  <div class="row">
    <div class="jumbotron">
      <h1>Trick or Treat</h1>
      <p>Click on a button for a spooky surprise 🎃 ...</p>
    </div>
  </div>

  <div class="row">
    <div class="container-fluid">
      <img id="image" style="padding: 10px; height: 300px; visibility: hidden"/>
    </div>
  </div>

  <div class="row">
    <div class="container-fluid" id="div_button">
      <button class="btn btn-warning btn-lg" type="button" onclick='change_image("monster")'>Trick!</button>
      <button class="btn btn-primary btn-lg" type="button" onclick='change_image("candy")'>Treat!</button>
    </div>
  </div>
</div>

Javascript

function change_image(file_prefix) {
  number = Math.floor(Math.random() * 6 ) + 1;
  var image_src = "images/" + file_prefix + number + ".png";
  document.getElementById("image").src = image_src;
  document.getElementById("image").style.visibility = "visible";
}

Read more about the project in the GitHub repo.

Updated: