Objectives and outcomes

In this tutorial we are going to learn about jqueryUI addclass and removeclass effects. addClass function adds a CSS class to the specified element where as removeClass function as the name suggest remove a class from the specified element. Example for the same is shown below:




Welcome to codeshot.in!!



HTML code:

<html>
<head>
<title>jQuery UI addClass Example</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
</head>
<body>
<div id="add_remove" class="element">
<br/>
Welcome to codeshot.in!!
</div>
<button class="button" id="add">Add Class</button>
<button class="button" id="remove">Remove Class</button>
</body>
</html>




CSS stylesheet

<style>
.element 
{
font-size:18px;
height: 50px;
background-color: #fff;
text-align:center;
color:#000;
font-weight:bold;
}

.change_style 
{
height:100px;
font-size: 30px; 
background-color: #585858; 
color: white;
text-align:center;
font-weight:bold;
}
</style>


Javascript

<script>
$(document).ready(function() {
$(".button").click(function() {
if (this.id == "add") {
$("#add_remove").addClass("change_style", "slow")
} else {
$("#add_remove").removeClass("change_style", "slow")
}
})
});
</script>


Here we have used addClass and removeClass function with two arguments one is the class which is needed to be added or to get removed with button click and second argument is the time for the effect to take place. this is used as a pointer to the current button object. Now in the next example we are going to add and remove multiple classes using the same function.



Welcome to codeshot.in!!



HTMLS code:

<html>
<head>
<title>jQuery UI addClass Example</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script
</head>
<body>
<p id="welcome">Welcome to codeshot.in!!</p>
<button class="button-1">Add class</button>&nbsp;&nbsp;
<button class="button-2">Remove class</button>
</body>
</html>


CSS stylesheet

<style>
.white 
{
background-color:#585858;
color: #fff; 
}

.large 
{ 
font-size: 4em; 
}

.spacing 
{ 
padding: 1em; 
}

#welcome
{
text-align:center;
}
</style>


Javascript

<script>
$(document).ready(function() {
$(".button-1").click(function() {
$( "#welcome" ).addClass( "white large spacing ", 3000 );
});
$(".button-2").click(function() {
$("#welcome").removeClass("white large spacing", 3000);
});
});
</script>


We can add and remove multiple classes by giving space between their names.