Is there a way to temporarily toggle classes with jQuery?

Incorporating ZeroClipboard, I have implemented the following code to alter the text and class of my 'copy to clipboard button' by modifying the innerHTML. Upon clicking, this triggers a smooth class transition animation.

client.on( "complete", function(client, args) {
            this.innerHTML = 'Copied to Clipboard';
            $( this ).removeClass( "btn-info" ).addClass( "btn-success", 357 );         
            });

I am looking for a solution that would enable me to make this class and innerHTML modification temporary. For instance, changing the class (to btn-success) only for a few seconds to indicate that the button was clicked, then automatically reverting back to its original class (btn-info). Also, removing the additional innerHTML = 'Copied to Clipboard'.

The desired class transition sequence would be: btn-info > btn-success > btn-info. Additionally, it should revert the innerHTML back to its original content (as each button has different innerHTML).

I attempted experimenting with toggleClass without much success so far.

Answer №1

One effective method is to implement a basic timeout feature

client.on("complete", function (client, args) {
    var html = this.innerHTML;
    this.innerHTML = 'Content Copied';
    var $this = $(this).removeClass("btn-info").addClass("btn-success");

    //clearing previous timer
    clearTimeout($this.data('completeToggler'))
    var timer = setTimeout(function () {
        $this.addClass("btn-info").removeClass("btn-success");
        $this.html(html)
    }, 2000);
    $this.data('completeToggler', timer);
});

To see it in action: Try the Fiddle


Another approach is using toggleClass()

client.on("complete", function (client, args) {
    this.innerHTML = 'Content Copied';
    var $this = $(this).toggleClass("btn-info btn-success");
    setTimeout(function () {
        $this.toggleClass("btn-info btn-success");
    }, 2000)
});

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

Display a static partial on a webpage using AJAX in Rails 3

So, I have 2 follow/unfollow forms in my Rails code. Here's the first one: <%= form_tag( {:controller => 'profile', :action => 'unfollow_topic' }) do %> <%= hidden_field_tag :topic_id, @topic.id %> <button ...

Steps for integrating an Angular 2 App into Express.js as a view

I am currently working on developing an Angular 2 app that requires data from a script running on the server. To achieve this, I am attempting to integrate my existing Angular app as a view within an express application, similar to the process demonstrated ...

Every time I use Axios with NextJS, I keep getting a frustrating 405 method not allowed

I am facing a challenging issue with this... Currently, I am using NextJS for the frontend and making a request to <frontend-domain>/api/auth/register from here. const changePassword = async (currentPassword, password) => { await axios.post(& ...

Issue encountered in AngularJS: struggling to store the localStorage item in the scope variable

I've been trying to save the values from window.localStorage.getItem('job_id.done_tasks') into a $scope variable, but I'm encountering difficulties. Can you please review my code? $scope.done_tasks = {}; $scope.done_tasks = window.loca ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Tips for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...

Using jQuery to modify CSS properties in the propertyName

With jQuery v1.6.4, I am attempting to dynamically format some objects. Take a look at my code snippet: <html> <head> <script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script> <script type="text ...

How can I show the configuration in Laravel?

After updating my pages to utilize an extended header for consistent content across all pages, I encountered an issue with the footer configuration. Whenever I attempt to retrieve a configuration from Laravel, it appears as normal text instead of being pro ...

The PHP JSON response is equipped with HTML headers

I'm facing an unusual issue with my PHP code. I'm trying to build a PHP page that sends JSON data back in response to a Jquery AJAX call. However, despite setting the content type as application/json, the response always contains the HTML header. ...

Exploring the features of React.js version 16

I'm confused about what {...props} does. I know it makes passing props easier, but what happens if there are no props to begin with? Take this example: const input = (props) => { let inputElement = null; switch(props.inputtype) { ...

Echo a JS variable into PHP and then insert a PHP file into an HTML element - a step-by-step guide!

Greetings to the wonderful community at stackoverflow, I am currently working on a variable code that allows for easy insertion of code from another file, such as a div. I am curious if it is possible to include a PHP file using JavaScript and JS variable ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

The process of querying two MySQL tables simultaneously in a Node.js environment using Express

My goal is to display both the article and comments when a user clicks on a post. However, I've encountered an issue where only the post loads without the accompanying comments. Here is the code snippet that I've been working with: router.get(&a ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

What is the best way to incorporate a style attribute into my EJS page content?

Having trouble with adding custom style. It seems to work, but there's an error displayed. Apologies for my poor english :( <div class="card card_applicant"> <div class="card_title" style="background-c ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

Preventing the user from using the mouse wheel until the CSS animation finishes

I am working with multiple functions that are triggered by scrolling the mouse wheel up and down. These functions must be called in a specific order, but the issue arises when users scroll quickly causing the CSS animations from the previous function to ...

I have successfully established a new channel, but I am having difficulty retrieving the unique identifier for it

After using the provided code to create a channel, I'm having trouble locating the channel ID needed for the next step in my function. This function is meant to move to a specific category and send a message to it. const buyid = generateID message. ...

The ESLint rule "eqeqeq" configuration is deemed incorrect

After successfully running eslint with the provided .eslintrc file, I encountered an issue when making a simple change to use 'standard' instead of 'airbnb-base' as the extend: module.exports = { root: true, parser: 'babel-esl ...

Navigating the challenges presented by CORS (Cross-Origin Resource Sharing) and CORB (Cross-Origin Read Blocking) when utilizing the FETCH API in Vanilla Javascript

Looking to update text on a website using data from a JSON file on another site? This scenario is unique due to restrictions - can't use JQuery or backend elements like Node/PHP. Wondering if vanilla JavaScript can solve the problem? While some worka ...