Toggle text and class onclick

In this example below you will see how to do a Toggle text and class onclick with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by linuxrick, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright linuxrick ©
  • HTML
  • CSS
  • JavaScript
    <body> 
  <p>Toggle text and color of a button</p>
<div id="activate" class="label-danger" >Deactivate</div> 
</body>

/*Downloaded from https://www.codeseek.co/linuxrick/toggle-text-and-class-onclick-ptjhb */
    body{text-align:center; margin-top:20px;}

.label-danger{
  background-color:#ff0000;
  padding:4px 14px;
  color:#fff;
}

.label-warning{
  background-color:#aaccee;
  padding:4px 14px;
}

#activate{
  border:1px solid #222;
  border-radius:6px;
   width:150px;
  margin:0 auto;
}




/*Downloaded from https://www.codeseek.co/linuxrick/toggle-text-and-class-onclick-ptjhb */
    $('#activate').click(function () { 
    var text = 'Activate';
    // save $(this) so jQuery doesn't have to execute again
    var $this = $('#activate');
    if ($this.text() === text) {
        $(this).text('Deactivate').toggleClass("label-warning label-danger");

    } else {
        $this.text(text).toggleClass("label-danger label-warning");;
        
    }
});


Comments