jQuery toggleClass example

by HYEONGJINKIM

HTML

<h1>jQuery toggleClass example</h1>

<p>This is paragraph1</p>
<p id="para2">This is paragraph2 (toggleClass effect)</p>
<p>This is paragraph3</p>
<p id="para4">This is paragraph4 (add/remove effect)</p>

<button id="addClass">Add class</button>
<button id="removeClass">Remove class</button>
<button id="addremoveClass">Add/Remove class</button>
<button id="toggleClass">toggle class</button>

CSS

.highlight {
  background: blue;
}

JavaScript

$("#addClass").click(function() {
  $('#para4').addClass('highlight');
});

$("#removeClass").click(function() {
  $('#para4').removeClass('highlight');
});

$("#addremoveClass").click(function() {
  if ($('#para4').is('.highlight')) {
    $('#para4').removeClass('highlight');
  } else {
    $('#para4').addClass('highlight');
  }
});

$("#toggleClass").click(function() {
  $('#para2').toggleClass('highlight');
});