Create a function to allow the div to flash a different color temporarily upon being clicked

I've set up my website using divs as buttons, and when they're clicked they add ingredients to my burger.

JS:

<div id="ingredientBox">
        <Ingredient
        ref="ingredient"
        v-for="item in currentIngredients"
        v-on:increment="addToBurger(item)"
        :item="item"
        :lang="lang"
        :ui-labels="uiLabels"
        :key="item.ingredient_id">
      </Ingredient>
    </div>

Styling with CSS:

.ingredient {
  border: 1px solid #f5f5f28a;
  padding: 0.8em;
  width: 23vh;
  height: 19vh;
  background-color: green;
  border-radius: 25px;
  margin: 10px;
  text-align: center;
}

I am now looking to make the div react visually when clicked by changing its color momentarily (for like 0.2 seconds). I have searched for solutions but only found ways to change the color permanently. Is there a simple method to achieve this temporary color change effect?

Answer №1

To achieve this effect, you can utilize CSS keyframe animation:

@keyframes animate-burger-button {
  0% {
    background: red;
  }
  50% {
    background: yellow;
  }
  100% {
    background: green;
  }
}

#ingredientBox:active {
  animation: animate-burger-button 0.8s forwards;
}

Additionally, consider using a button instead of a div for better accessibility.

Answer №2

If you want to change the color of #ingredientBox when it is active on a webpage, you can use the following CSS:

#ingredientBox:active {
  color: red;
}

Answer №3

If you want to dynamically add and remove a class from a button, you can utilize the `setTimeout` function in JavaScript.

Here is an example code snippet:

buttonTrigger() {
   element.classList.add('somesyle'); // Add a color-changing class to the element

   setTimeout(() => {
       element.classList.remove('somestyle'); // Remove the class after 0.2 seconds
   }, 200)

}

Additional Tip:

In addition to using `setTimeout`, you could also consider using CSS `keyframes` as suggested by @AlexanderKaran for achieving similar effects.

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

Making an Ajax request to retrieve progress information by utilizing IProgress

I have encountered an issue with my code involving 2 ajax API calls. One call fetches data through a lengthy process, while the other retrieves progress values using the IProgress interface and runs every 5 seconds. The value from ReportProgress successf ...

The Swiper slider is unable to display several views at once in the slider layout

I recently started using the amazing swiper slider plugin available here My goal is to replicate the demo-no-210 from that repository. Here is the code snippet I am working with: index.html <!DOCTYPE html> <html> <head> <meta ...

What's the best way to use Flexbox to center a component with a "fixed width"?

As I work on my component, here is the code snippet from my highest parent, App.component: app.component.html <div class="wrapper_flex"> <div style="width:400px; background-color: pink;"></div> <div style=& ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Using AngularJS to dynamically apply a class to multiple elements within an ng-repeat loop based on a certain condition

I am having trouble finding any resources on this topic and I was hoping for some assistance. Currently, I am retrieving information from a database and using AngularJS to perform an ng-repeat based on specific filters. <tr ng-repeat="data in filter ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Utilizing JQuery's printThis Plugin in Combination with the Style Attribute

I am currently working on a JavaScript app and I am trying to implement a button that will allow users to print a specific div. To achieve this, I am utilizing a jQuery plugin called printThis (github link) as well as attempting to use window.print(). $(" ...

Adding two cookies to the Set-Cookie jar

Recently I created a new class with some methods to handle cookies in Node.js: var qs = require('querystring'); class Cookie { constructor(req, res) { this.req = req; this.res = res; } get(name) { ...

Double Triggering Problem Arises During Partial Refresh

My dojo button bar is connected to a csjs function that performs a partialrefreshget() on a datable control. The datasource for the datatable control is a view. Within the this.keys property, I have implemented logic to check if the partialrefresh was ini ...

Guide to incorporating text with a hover overlay image using HTML, CSS, and JavaScript exclusively

Here is some code for displaying hidden information on shape hover, but there are a couple of issues: 1. When the font size is reduced to 24px, the dark grey background does not cover the entire shape. 2. I want to include text that appears with the hover ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

What is the best way to transform a CSS linear gradient into JavaScript code for use in a React Native application

Struggling to convert my input data from Figma CSS into a format that works with react native. Are there any helpful libraries for this task? If so, how should I go about writing it out? The CSS code in question can be found here. ...

Is there a way to trigger a JavaScript alert to notify whether a record already exists or not within a PDO MySQL insert query?

I am working with a MySQL database and looking to insert data from a PHP form using PDO connect. Can anyone help me figure out how to display a JavaScript alert popup in the following scenarios: When a record already exists. When a new record has been ad ...

Retrieve specific values from columns for dynamically generated rows using JavaScript

Currently, I am in the process of creating a dynamic table using PHP. In my screenshot, there are two rows with multiple columns. Each column in both rows has the same id. For example, the column for Monday has id="mon" in the first row and also id="mon" i ...

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...

Extract the variables from the while loop

Is there a way to store the variables outside of the while loop? For instance, I have a slideshow displaying images for each category and a button that when clicked leads to the image gallery related to that category. However, due to graphical reasons, the ...

Tips for effectively creating and appending elements using JavaScript

Code Sample var result=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query}, function(data) { ... question. }); Query: In order to display each tweet result, I want to ...

Tips for showcasing messages in a .dust file with connect-flash and express-messages in a Node application

I am currently working with Nodejs, Expressjs, and Kraken. I have been trying to display a message when a product is added on the index page, but despite several attempts to configure it, the messages are still not appearing as expected. Below is my config ...

Exploring the concept of inheriting AngularJS modules

I am intrigued by the behavior of AngularJS. I am wondering if AngularJS modules inherit dependencies from other modules. Let's consider the following structure: var PVNServices = angular.module('PVN.services', []); PVNServices.factory(&a ...

Using Bootstrap 4 navtabs alongside accordions to utilize the show.bs and hide.bs functionalities

Is there a method to activate the "Maintab 2 Content" and display the accordion content for "Collapsible Group Item #2" when clicking on the "Button for Maintab 2"? I am trying to implement similar functionality on other tabs as well, but I'm struggli ...