Search code examples
javascriptjquerycsszeroclipboard

jQuery: Temporarily toggleClass / addClass, removeClass?


I'm using the following code with ZeroClipboard to change the innerHTML text and class of my 'copy to clipboard button'. Once clicked, this animates the class transition.

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

Is there a way in which I could make this change of class and innerHTML temporary? i.e. change the class (to btn-success) for only a few seconds to indicate that the button was clicked, and auto revert back to it's original class (btn-info)? And remove the added innerHTML = 'Copied to Clipboard'

So the class transition would be 'btn-info' > 'btn-success' > 'btn-info'. And revert the innerHTML back to whatever it was beforehand (each button has different innerHTML).

I've tried experimenting with toggleClass, but haven't had much luck.


Solution

  • Try using a simple timeout

    client.on("complete", function (client, args) {
        var html = this.innerHTML;
        this.innerHTML = 'Copied to Clipboard';
        var $this = $(this).removeClass("btn-info").addClass("btn-success");
    
        //clear 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);
    });
    

    Demo: Fiddle


    also try using toggleClass()

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