Home > Back-end >  How to change the color/size/etc of dynamically created buttons in javascript?
How to change the color/size/etc of dynamically created buttons in javascript?

Time:07-21

I have created dynamic buttons in vuejs where each button represents a different answer to a question.
My goal is: when I get the answer wrong, the correct option is highlighted in green until the next question is shown.
Is it also possible to change other settings of these "BaseButtons" with CSS? How can I do this?

<template>
  <div >
     <BaseButton  
     v-for="options in optionsAnswers" 
     :key="options.id" @click="handleAnswer(options)">
       {{options.ans}}
     </BaseButton>
  </div>
</template>
methods:{
  handleAnswer(options){
    if (options.id === this.correctAnswer){
      this.playerHit = true;
    }
    else {
      this.opponentHit = true;
      
    }
    this.nextquestion();
  },

CodePudding user response:

One option is to create css classes with styles you need and append them to BaseButton component depending on your conditions

CodePudding user response:

Have a look at this one:

HTML block:

<template>
  <div >
    <BaseButton
      v-for="(options, index) in optionsAnswers"
      :key="options.id"
      
      :
      @click="handleAnswer(options, index)"
    >
      {{ options.ans }}
    </BaseButton>
  </div>
</template>

JavaScript block:


<script>
export default {
  data() {
    return {
      correctAnsIndex: null,
    }
  },
  methods: {
    handleAnswer(options, index) {
      if (options.id === this.correctAnswer) {
        this.playerHit = true
        this.correctAnsIndex = index
      } else {
        this.opponentHit = true
        this.correctAnsIndex = null
      }
      this.nextquestion()
    },
  },
}
</script>

CSS block:


<style>
.red-button {
  background: red;
  color: white;
  font-weight: 700;
}

.green-button {
  background: green;
  color: white;
  font-weight: 700;
}
</style>
  • Related