Multi
Multi

Reputation: 23

Add background color when click a button vue js

I'm building an app with VUE JS, using different components.

In one of them, I have a button that I would like that change the color when I click on it. This button is choosing different items from a table, so when I press that button I want that the background of that button change to red for example to know which ones I have clicked.

<template>
  <button class="mdc-icon-button material-icons"  @click="doMultiple">delete_outline</button>  
</template>

This is the button. How can I add there the style when button be clicked?

Thanks in advance!

Upvotes: 2

Views: 14573

Answers (3)

Pierre Said
Pierre Said

Reputation: 3820

You can use conditional binding to dynamically add a class to an element.

https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: "#app",
  data: {
    deleteClicked: false
  },
  methods: {
    onClick() {
      this.deleteClicked = true;
    }
  }
})
.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div :class="{ red : deleteClicked }">
    Item
    <button @click="onClick">
      Delete
    </button>
  </div>
</div>

Upvotes: 2

Visal
Visal

Reputation: 477

This is my version of linking js variables to vue js with watch method. This is immediate and will change as you drag the cursor along the color picker. Check the code snippet below. CSS is also required.

let vue = new Vue({
  el: "#view",
  data: {
    bg: "#FFFFFF",
    color: "#000000",
  },
  watch: {
    bg: css_variable_watcher("--bg"),
    color: css_variable_watcher("--color"),
  },
});
//Watcher for CSS
function css_variable_watcher(name, suffix = "") {
  return {
    immediate: true,
    handler(new_value, old_value) {
      document.documentElement.style.setProperty(name, new_value + suffix);
    },
  };
}
body {
  background-color: var(--bg);
  color: var(--color);
}
<body>
  <div id="view">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <input type="color" v-model="bg">
    <input type="color" v-model="color">
    <button type="button" v-on:click="[color, bg] = [bg, color]">Swap Text and Background Color</button>
    <p>Hello. I am a Paragraph. Select the first input to change bg color and second input to change text color.</p>
  </div>
</body>

Upvotes: 0

Sarah Sundar
Sarah Sundar

Reputation: 38

Call the css class with either of the option

.mdc-icon-button material-icons:active{
    background:red;
}
OR

.mdc-icon-button material-icons:focus{
    background:red;
}

Upvotes: 1

Related Questions