Wednesday, 29 July 2015

Toggle two CSS classes using jQuery

Leave a Comment

First create two paragraphs and a button in HTML.

<h3>This is heading</h3>
<p>jQuery is a fast, small and feature-rich <b>JavaScript</b> library.</p>
<p>'Write less: Do more'</p>
<button id="button">Click here to toggle classes</button>

Now create two different classes in CSS.

<style>
.clr1{
background-color:#CCF;
color:#60F;
}
.clr2{
background-color:#FC3;
color:#360;
}
</style>

Now the jQuery part. Here we want to toggle the classes when button is pressed. Lets see how its done.

$(document).ready(function() {
$("p").addClass("clr1");
$("#button").click(function(){
$("p").toggleClass("clr1 clr2");
});
});

Lets look at the full code.

<style>
.clr1{
background-color:#CCF;
color:#60F;
}
.clr2{
background-color:#FC3;
color:#360;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("p").addClass("clr1");
$("#button").click(function(){
$("p").toggleClass("clr1 clr2");
});
});
</script>

<h3>This is heading</h3>
<p>jQuery is a fast, small and feature-rich <b>JavaScript</b> library.</p>
<p>'Write less: Do more'</p>
<button id="button">Click here to toggle classes</button>

That’s it. Now when you press the button paragraph color is changed or toggled between two classes.

0 comments:

Post a Comment

.