jQuery Form How to - Add/remove class when button clicked








Question

We would like to know how to add/remove class when button clicked.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.10.1.js'></script>
<style type='text/css'>
.bodyRed {<!--from www .j a  va2 s  .  c  om-->
  background-color: red;
}
</style>
<script type='text/javascript'>
$(function(){
    var $body = $('body'),
        $button = $('#lumiere');

    $button.on('click', function(event) {
        if($body.hasClass('bodyRed')) {
            $body.removeClass('bodyRed');
            $button.text('2');
        } else {
            $body.addClass('bodyRed');
            $button.text('1');
        }
    });
});
</script>
</head>
<body>
  <button id="lumiere">1</button>
</body>
</html>

The code above is rendered as follows: