Incorporate a CSS transition duration for switching classes with JavaScript

I need assistance with adding a transition time to my JavaScript toggle class function. I had previously coded it but have now forgotten how to do so. Any guidance would be highly appreciated.

<!DOCTYPE html>
<html>
<head>

<style type="text/css>
#div{
    width: 200px;
    height: 150px;
}
.class1 {
    color: #f00;
    background-color: #2fadac;
}

.class2 {
    color: #00f;
    background-color: #c33;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
    this.classList.toggle('class1');
    this.classList.toggle('class2');
    style.cssText ="-webkit-transition: all 0.5s ease-in-out;";
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>

Any assistance would be greatly appreciated.

Answer №1

Consider adding the transition rule directly to your target class.

.class1 {
    color: #f00;
    background-color: #2fadac;
   -webkit-transition: all 0.5s ease-in-out;
}

.class2 {
    color: #00f;
    background-color: #c33;
    -webkit-transition: all 0.5s ease-in-out;

}

View Demo

Alternatively, you can define the transition rule in a separate class:

CSS:-

.class1 {
    color: #f00;
    background-color: #2fadac;
}

.class2 {
    color: #00f;
    background-color: #c33;
}
.transition{
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition:all 0.5s ease-in-out;
  -o-transition:all 0.5s ease-in-out;
  transition:all 0.5s ease-in-out;
}

HTML:

<div id="div" class="class1 transition">click here</div>

View Demo

Answer №2

Implement a transition in your CSS stylesheet

#div{
    width: 200px;
    height: 150px;
    -webkit-transition: all .5s ease-in-out;
    -moz-transition: all .5s ease-in-out;
    -ms-transition: all .5s ease-in-out;
    -o-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out;
}

Check out the DEMO here

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

Choosing a tab on a website using Python and Selenium

Displayed above is an image of tab codes found on a web page: https://i.sstatic.net/M54VH.png The tabs are named Overview, Information, and Audit (Please refer to the top part of the image). While I am able to open the tab by clicking with a mouse, I am f ...

What is the method for selecting an li element within a ul list using Selenium in Python?

My goal is to automate the process of clicking on 'National Data' on a specific website using the Selenium package in Python. The website I am referring to can be found at . Although I attempted to achieve this automation, I encountered difficul ...

Testing Vue Component with Cypress revealed that the function getActivePinia was triggered without an active Pinia instance

Below are the code snippets I'm working with: Test.vue <template> <button v-show="store.common == 'hi'" @click="func"> hello world </button> </template> <script setup> import {mainS ...

Is there a reason why the slide up feature is not working when I include the ul tag?

I need help with a jQuery code that will pull up/slide up an Html "p" tag when my page finishes loading. This snippet of jQuery code seems to be working fine: $(function () { $('.graybgc').slideUp(0); }); This is the HTML structure: <p ...

An error has occurred in Angular5 and Three.js: 'Scene1' property is undefined

Running into an issue with my angular5 website integrated with Three.js. I keep getting an error message that says: Cannot read property 'Scene1' of undefined when trying to add an object to the Scene. Any suggestions on how to properly define th ...

Tips for accessing id from $http.get in angular.js

Hello everyone, I'm new to Angular.js and currently learning it. I need help in retrieving data from the following API URL: . I am unsure how to implement this in my controller.js file. Below is the code I have so far, can someone please guide me on h ...

A guide on enabling or disabling a combobox in vuejs3

In VueJs 3, I am looking for a way to toggle the Disable/Enable status of a combo-box based on a specific property. Below is my code snippet: <template> <div class="combobox"> <label for={{selector_name}}> <p> ...

Modify certain user configurations without altering all settings in one specific form using PHP and MySQL

I am in the process of developing a PHP website with data stored in a MySQL database. Currently, I have completed the sign-up, login, and logout functionalities. However, I am looking to enhance user experience by adding a section where users can adjust th ...

Horizontal compression applied to background image

After following a suggestion ("css only technique number 1" found here http://css-tricks.com/perfect-full-page-background-image/), I experimented with using an inline img element and CSS to create a background image that would occupy the entire browser win ...

"Unlock the power of Passport.js: A guide to leveraging async rendering for email templates

Currently, my setup involves running Express with Sequelize/MariaDB and Passport.js to handle user authentication. Everything seems to be working smoothly except for the activation email that needs to be sent out after a user signs up. Despite having the ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Extension ConfirmButtonExtender

There is a scenario where I need to skip the ConfirmButtonExtender based on the value of another field in the page. Typically, when a user clicks on my "Cancel" button, a modal popup appears using the confirmbuttonextender and the modalpopupextender. The ...

Automatically updating the JavaScript content on a webpage without having to refresh the entire HTML page, based on the changing

Is there a way to adjust the opacity change rate of my nav bar automatically without the need to refresh the page? The current opacity change rate is based on the width of the window, but once the page is loaded, adjusting the width does not affect the rat ...

The value of useEffect does not change even after it is defined in ReactJS

I am working on a component where I need to fetch data from an API after it has been rendered, and store the response in a useState value. However, when attempting to set the state using the useEffect callback after fetching the API, nothing seems to be w ...

In Internet Explorer 11, React 15.4.1 does not support using objects as valid child components

When trying to render a collection of children in React, make sure to use an array instead of objects. If you encounter the error "Objects are not valid as a React child," consider wrapping the object using createFragment(object) from the React add-ons. Do ...

Ways to display a component using *ngIf else

As a beginner in angular, I decided to create a simple app to help me learn the basics. The concept of my app involves two players entering their names in separate input fields. Once they click a button, the game begins and displays their names along with ...

My search field in Safari (desktop) doesn't respond to jQuery's .focus() function

My website has a hidden search field that appears when the user clicks on the search icon. I want to automatically bring focus to the search input so users do not have to click twice. This feature works perfectly in Chrome, but not in Safari (desktop). I t ...

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...