How to toggle a class on button click using jQuery

Sometimes you'll want to toggle a class on and off by clicking a button.

In the below example, when the 'Toggle class' button is clicked, the orange block's background is changed to red, through the addition of a class with a red background. When the button is clicked again, the added class is removed, reverting the background to the original orange:

Toggle class:

The code for the above is as follows:

The CSS:

This will need to go preferably in your style sheet, or else in your document head between the style tags. Note the CSS transition for a smooth changeover between the orange and red.

.orange-block {
position:relative;
margin:20px 20px 20px 5px;
width:200px;
height:200px;
background:#ff8300;
transition:.3s ease-in-out;
-moz-transition:.3s ease-in-out;
-webkit-transition:.3s ease-in-out;
}

.red-block {
background:#fe3b1f;
}

button {
font-family:Arial, Helvetica, sans-serif;
color:white;
background:blue;
padding:14px;
border:none;
margin:0 8px 0 0;
cursor:pointer;
font-size:.9em;
}

The HTML:

<div class="orange-block"></div>

<button id="toggleClass">Toggle Class</button>

Include jQuery before your closing body tag:

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Then add the javascript:

<script type="text/javascript">

$(function () {

$('#toggleClass').click(function () {

$('.orange-block').toggleClass('red-block');

});

});

</script>