Toggle Class JavaScript
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
- CSS/JavaScript
- Example
<a href="#!" class='navToggle'>On click Show or Hide class</a> - Click event <div class="tabsClick">...</div> - Class name where the toggle method attachecd the event class
//CSS .tabsClick { display: none; } .showhide { display: block; } //Javascript <script> $(document).ready(function(){ $(".navToggle").click(function(){ $('.tabsClick').toggleClass("showhide"); }); }); </script>
<!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>
In this tutorial we learn that how to show and hide div on single click
You can customize this code further as per your requirement.
Another Option for addClass and removeClass.
$('.navToggle').on('click', function(){ $(.tabsClick).addClass('showhide'); }); $('.navToggle').on('click', function(){ $('.tabsClick').removeClass('showhide'); });