Change CSS Class Style className Toggle Tutorial
Learn to change, toggle and swap CSS classes using JavaScript event handling. We are using the className property to check and also change the CSS class assigned to HTML elements. In the second code example we use an array to group sibling elements for swapping a class change between them all.
Example 1 from the video lesson shows how to create a function that toggles between two CSS classes as an element is repeatedly clicked. It demonstrates On and Off logic.
<!DOCTYPE html>
<html>
<head>
<style>
.class1{ float:left; margin:10px; background:#09C; width:100px; height:100px; cursor:pointer; }
.class2{ float:left; margin:10px; background:#0C0; width:100px; height:100px; cursor:pointer; }
</style>
<script>
function toggleClass(el){
if(el.className == "class1"){
el.className = "class2";
} else {
el.className = "class1";
}
}
</script>
</head>
<body>
<div class="class1" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
</body>
</html>
Example 2 from the video lesson shows how to swap the class change between an array of child elements.
<!DOCTYPE html>
<html>
<head>
<style>
.class1{ float:left; margin:10px; background:#09C; width:100px; height:100px; cursor:pointer; }
.class2{ float:left; margin:10px; background:#0C0; width:100px; height:100px; cursor:pointer; }
</style>
<script>
function toggleClass(el){
var kids = document.getElementById('menu1').children;
for(var i = 0; i < kids.length; i++){
kids[i].className = "class1";
}
el.className = "class2";
}
</script>
</head>
<body>
<div id="menu1">
<div class="class2" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
<div class="class1" onclick="toggleClass(this)"></div>
</div>
</body>
</html>