Implement a feature in Vue.js where clicking a button changes the background color

I'm working on an app using VUE JS and incorporating various components.

Within one of the components, I have a button that I want to change color when clicked. This button is responsible for selecting different items from a table, so I'd like it to change its background color to red, for example, whenever it's clicked in order to track selections.

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

This code snippet shows the button in question. What would be the best way to incorporate styling changes upon clicking the button?

Your help is much appreciated!

Answer №1

One way to dynamically add a class to an element is through conditional binding.

Check out more about this in the following link: 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>

Answer №2

Utilize the css classes by choosing one of these options

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

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

Answer №3

Here's a unique way to connect JavaScript variables to Vue.js using the watch method. This setup allows for immediate updates as you move the cursor on a color picker. Take a look at the snippet below which also requires CSS styling.

let vue = new Vue({
  el: "#view",
  data: {
    bg: "#FFFFFF",
    color: "#000000",
  },
  watch: {
    bg: css_variable_watcher("--bg"),
    color: css_variable_watcher("--color"),
  },
});
//CSS Watcher
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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one create custom JavaScript UI controls for a UWP application?

I am currently working on a UWP application and I am looking to incorporate JavaScript HTML5 based UI components. Is there a method to integrate this UI into a UWP application? My UI is completely developed using JavaScript, jQuery, CSS, and HTML5, and I w ...

What is the best way to retrieve data in Nodejs from a different execution context?

My goal is to continuously fetch data from a website that updates frequently using MutateObservable. In order to achieve this, I am utilizing Puppeteer as my scraper since the data changes every second, requiring a browser to remain open constantly. For t ...

Transforming jquery code into Angularjs code

I am currently working on a jQuery method that adds a 'selected' class to table rows and handles click events. Here is the code: $('.niGridTable table tr').addClass('selected').end().click(function (event) { event = ...

Div automatically shifts to center position when other div elements vanish from view

I am new to jquery and currently working on a basic website. The site consists of three boxes, each of which, when clicked, causes the other two to fade out using the .fadeOut('slow'); method. However, there is an issue - all of the boxes are enc ...

Executing JavaScript code within a Django application to load a file

Utilizing a JavaScript tool called jQuery FileTree within my Django application has presented a dilemma. This particular JavaScript requires access to a python script path, but incorporating Django template tags directly into JavaScript poses an issue. Wi ...

Using ASP.NET MVC to map FormData with an array to a model class

I am currently facing an issue with mapping a list of objects in a FormData to my ASP.NET MVC Model class at the controller. I have successfully sent the FormData over to the server-side, but I am unable to bind any value. Can someone provide guidance on h ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

What potential side-effects could occur from cloning the entire state object in React?

Upon reviewing a React code base I'm currently working on, I've noticed a recurring pattern that concerns me regarding potential bugs. Here is an example of the code in question: const newState = Object.assign({}, {}, this.state); newState.x = ...

The issue of "undefined is not a function" is arising when trying to use the session in NHibernate with a mongo store

In my MongoDB database, I have a collection named 'Sessions' within the 'SessionStore' to store session state. To manage sessions, I am using express-session. Below is the code snippet used to set up sessions: var session = requi ...

Loop through, conditionally display, and perform comparisons on different components of a date object

I am currently working on creating an event listing using Angular and I am facing a challenge. I want to dynamically add a year and month element between event listings based on changes in the year/month. <body ng-controller="CalendarController"> & ...

Modifying script variables using the Chrome console

There is a button on the website that looks like this: https://i.sstatic.net/G7PBF.png Clicking on this button triggers the following script: https://i.sstatic.net/rIdLW.png function count(){ let downloadTimer; var timeleft = 30; downloadTimer = setInte ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

The application of Uglify to eliminate console logs can be inconsistent in its effectiveness

Having some trouble with my Vue3 app. I've implemented UglifyJS to remove console.logs in production environments, but it seems to be inconsistent. Sometimes it works fine, other times not so much. Every time I have to rebuild and hope for the best. I ...

Utilize Jquery to copy the parent element to the text field with just a click

I'm looking to have 4 buttons placed next to each URL, so that when you click on a button, the parent URL is copied to the corresponding text field of that button. I believe using jQuery would be the easiest way to achieve this, but I'm not sure ...

Obtaining the scene's coordinates in Three.js

Struggling with a coding issue, I've scanned various discussions that don't quite address my specific problem. Any assistance would be greatly appreciated. In my HTML document, I am using the three.js library to create a scene titled scaledScene ...

What is the best method to adjust the size of a three.js renderer to match a specific webpage element?

I'm looking to adjust the size of the renderer to match that of an element on my webpage. When I use renderer.setSize(window.innerWidth, window.innerHeight), it sets the renderer to fit the entire window. init() { let map = document.getElemen ...

What is the most effective method for discerning the availability of fresh data?

Many highload websites are able to notify their users of new messages or topics in real-time without the need for page refreshing. How do they achieve this and what approaches are commonly used? There appear to be two main methods: Continuously querying ...

Executing an HTML webpage with npm package.json file

I have recently discovered package.json files and am new to using them. I have created an HTML webpage using three files: HTML, CSS, and JavaScript. Currently, I open the HTML file directly in my browser but have been advised to use a package.json file a ...