How to add or remove a class on button click using jQuery

Sometimes you'll need to add a class to an element on the click of a button with the option to remove the class on the click of another button.

In the below example, when the 'Add class' button is clicked, the green block's background is changed to blue, through the addition of a class with a blue background. When the 'Remove class' button is clicked, the added class is removed, reverting the background to the original green:

Add and remove 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 green and blue.

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

.blue-block {
background:#00addc;
}

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="green-block"></div>

<button id="addClass">Add Class</button>
<button id="removeClass">Remove Class</button>

Include jQuery after your closing body tag:

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

Then add the javascript:

<script type="text/javascript">

$(function () {

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

$('.green-block').addClass('blue-block');

});

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

$('.green-block').removeClass('blue-block');

});

});

</script>