Home > OS >  How to add an onClick animation?
How to add an onClick animation?

Time:09-09

I've been making a text adventure game with a tutorial. The thing I want to add is to make the options I select fade out slowly.

The thing is, if I try to change classes I break it and it is not playable anymore, because there is already a few class changes and I couldn't grasp how I could do it without breaking the game. I can use a hover effect transition: all 1s ease-out but what I'm trying to do is to make this happen when I click on the option, not when I hover on it. I also tried to change selectOption function but it always gave an error when I add something.

The html of the options:

<div id="text">Text</div>
<div id="option-buttons" >
  <button >Option 1</button>
  <button >Option 2</button>
  <button >Option 3</button>
  <button >Option 4</button>
</div>

The functions and html elements of the game:


const textElement = document.getElementById('text')
const optionButtonsElement = document.getElementById('option-buttons')

let state = {}

function startGame() {
  state = {}
  showTextNode(1)
}

function showTextNode(textNodeIndex) {
  const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
  textElement.innerText = textNode.text
  while (optionButtonsElement.firstChild) {
    optionButtonsElement.removeChild(optionButtonsElement.firstChild)
  }

  textNode.options.forEach(option => {
    if (showOption(option)) {
      const button = document.createElement('button')
      button.innerText = option.text
      button.classList.add('button')
      button.addEventListener('click', () => selectOption(option))
      optionButtonsElement.appendChild(button)
    }
  })
}

function showOption(option) {
  return option.requiredState == null || option.requiredState(state)
}

function selectOption(option) {
  const nextTextNodeId = option.nextText
  if (nextTextNodeId <= 0) {
    return startGame()
  }
  state = Object.assign(state, option.setState)
  showTextNode(nextTextNodeId)
}
An example of options:

const textNodes = [
  {
    id: 1,
    text: 'You wake up in a strange place and you see a jar of blue goo near you.',
    options: [
      {
        text: 'Take the goo',
        setState: { blueGoo: true },
        nextText: 2
      },
      {
        text: 'Leave the goo',
        nextText: 2
      }
    ]
  },

How can I add an onClick animation to those options?

CodePudding user response:

You can try to add the function/animation directly into your code. Just like this:

<div id="text">Text</div>
<div id="option-buttons" >
  <button  onclick="animation(this)">Option 1</button>
  <button  onclick="animation(his)">Option 2</button>
  <button  onclick="animation(this)">Option 3</button>
  <button  onclick="animation(this)">Option 4</button>
</div>

function animation (obj) {oby.class = "animation"}

You would need to specify the class animation in CSS.

  • Related