Toggle Class JavaScript | How to create JavaScript toggle class.
Learn how to create toggle class in JavaScript. toggleClass(); events toggles between adding and removing class names from the selected elements.
To Create a toggle class, it takes following steps: –
- Create a click event html on which toggle method call.
- Pass the class name where hide or show class want to add using toggle method.
- Write a JavaScript function for toggle class.
- One-line CSS have to write display none and display block depend upon need.
HTML
<a href="#!" class='navToggle'>On click Show or Hide class</a> - Click event
<div class="tabsClick">...</div> - Class name where the toggle method attached the event class
CSS / JavaScript
//CSS
.tabsClick {
display: none;
}
.showhide {
display: block;
}
//Javascript
<script>
$(document).ready(function(){
$(".navToggle").click(function(){
$('.tabsClick').toggleClass("showhide");
});
});
</script>
Example
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="bootstrap.min.css">
<title>Hello, world!</title>
<style>
.tabsClick {
display: none;
}
.showhide {
display: block;
}
</style>
</head>
<body>
<a href="#!" class='navToggle'>On click Show or Hide class</a>
<div class="tabsClick">...</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="jquery-3.3.1.slim.min.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".navToggle").click(function(){
$('.tabsClick').toggleClass("showhide");
});
});
</script>
</body>
</html>
Another Option for addClass and removeClass.
$('.navToggle').on('click', function(){
$(.tabsClick).addClass('showhide');
});
$('.navToggle').on('click', function(){
$('.tabsClick').removeClass('showhide');
});
Hide and show div using JavaScript.
In this tutorial we learn that how to show and hide div on single click.
toggleClass(); method for show and hide div on single click.
You can customize this code further as per your requirement.