Learn jQuery addclass removeclass methods onclick

On 5/25/2015

Using the jQuery addClass() and removeClass() methods, we can dynamically add/remove css class(es) of an HTML element. The addClass method does not replace any existing classes but appends to them. The removeClass method removes the css classes of an element if exists. To add/remove more than one class at a time separate them with a space.

Here goes the syntax for addClass() removeClass() methods,

jquery addclass removeclass syntax

Recommended Read: Use PHP json_decode function to parse json object and insert into MySQL Database

Example

I want to change the color and size of the texts in a page when a checkbox is checked. To accomplish this, I'm going to write a css class and add it when the checkbox is checked and remove it when unchecked.

So I'll create a html page and add a checkbox and a paragraph element.

HTML Markup
<input id="colors" type="checkbox"><label>Red</label>
<p>I am a text</p>

Next add these CSS styles to the page.

CSS Styles
p {
     color: black;
     font-size: 24px;
}

.red {
     color: red;
     font-size: 30px;
     font-weight: bold;
}

Next write the jQuery script for toggling the css class named "red".

jQuery Script
$("#colors").click(function() {
     if ($("#colors").is(':checked'))
          $("p").addClass("red");
     else
          $("p").removeClass("red");
});

Recommended Read: Enable Disable group of HTML Elements with Checkbox using jQuery

Here is the complete code for the example.

<!DOCTYPE html>
<html>
<head>
<title>jQuery Add Remove Class Demo</title>
<meta charset="utf-8" /> 
<script src="js/jquery-1.10.2.js"></script><!--include jquery library-->
<style>
p {
     color: black;
     font-size: 24px;
}

.red {
     color: red;
     font-size: 30px;
     font-weight: bold;
}
</style>
</head>
<body>
     <input id="colors" type="checkbox" /><label>Red</label>
     <p>I am a text</p>

     <script type="text/javascript">
     $("#colors").click(function() {
          
          if ($("#colors").is(':checked'))
               $("p").addClass("red");
          else
               $("p").removeClass("red");
     });
     </script>
</body>
</html>

That's it. Hope you'd have enjoyed this jQuery tutorial for addclass removeclass methods. Meet you soon in another one interesting tutorial.

Last Modified: May-25-2015

No comments:

Post a Comment

Contact Form

Name

Email *

Message *