Fun Game: Click the button if you can

Sadat Jubayer

Sadat Jubayer

November 23, 2021

2 min read

This article will show you how you can build this moving button game with a simple trick!

The output will be like this:

Moving button

You need to know basics of

  • HTML
  • CSS
  • JavaScript

HTML Sturcture

Just a button! That's all you need on the HTML

index.html
<button>
  Click me
</button>

CSS

The CSS file contains the basic styles for the Body and the button. And the button is positioned absolutely so that it can be moved by the property Top and Left. Initially, the button is centered with the top 50% and left 50%. To center it perfectly, I have used the transform property, which moves the button itself.

styles.css
body {
  margin: 0;
  padding: 0;
  background: #1B8A77;
  min-height: 100vh;
}

button {
  background: #A3C3D0;
  border: none;
  padding: .5rem 1rem;
  border-radius: 4px;
  color: #060607;
  font-weight: bold;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

JavaScript - the trick

When the user moves the mouse over the button, the position of the button will be changed. For this, we'll use the top and left the property; this is the trick.

You can change you css sytles using JS, learn more about this

app.js
const button = document.querySelector('button');

button.addEventListener('mouseover', ()=> {
  button.style.top = `${Math.random() * 400}px`;
  button.style.left = `${Math.random() * 400}px`;
})

// if you can click the button
button.addEventListener('click', ()=> {
  alert('you did it!!')
})

Can you click the button?

Yes, you can click the button; there is a trick! Find it by yourself 😉

Source code