Blog Archive

jQuery add or remove class dynamically on button click

jQuery has addClass() and removeClass() methods which makes it really easy to dynamically add or remove CSS class from HTML page elements. In this example we are going add and remove a class from the paragraph based on a button click. Here is how to use ...


jquery add remove class onclick
jquery add remove class onclick

<html>
<head>
<title>jQuery add and remove CSS class example</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />
<style type="text/css">

.shaded {
 background-color: #eeeee0;
}

</style>
<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function() {
          
         $("#addClass").click(function () {
          $('#paragraph1').addClass('shaded');
            });
         
            $("#removeClass").click(function () {
          $('#paragraph1').removeClass('shaded');
            });
         
        });     
    </script>

</head>
<body>
 <fieldset>
   <legend>jQuery dynamically ADD and REMOVE CSS class</legend>

   <p id="paragraph1">
    <label for="myInputText1">
     My first input text is here:
    </label><br /> 
    <input
     id="myInputText1" type="text" name="inputBox" />
   </p>
   <p id="paragraph2">
    <label for="myInputText2">
     My second input text is here:
    </label><br /> 
    <input
     id="myInputText1" type="text" name="inputBox" />
   </p>
   <input id="addClass" type="button"
     value="Add background color" />
   <input id="removeClass" type="button"
     value="Remove background color" />  
 </fieldset>
</body>
</html>

No comments :

Post a Comment