A toggle function in JavaScript is a very handy concept to interchange between two states—usually on and off of an element. It can be showing or hiding elements, switching CSS classes, or toggling boolean values. In this post, we will guide you through different popular techniques to create toggle functions in JavaScript with real-world code examples, explanations, and best practices.
Table of Contents
What is a toggle function?
A toggle function is a process to alter between two different values or states. It is like flipping a switch: while you click on it, the light turns on, and if you click on it again, the light turns off. In JavaScript, we can implement this behavior via the use of conditional statements and event listeners.
Why use a toggle function in JavaScript?
Toggle functions are used for:
- Improving User Experience: Make elements interactive and engaging.
- Simplifying Code: Reduce criticality by using a single, easy-to-understand function to switch element states.
- Enhancing Performance: JS can efficiently manage element states without reloading the page.
1. Implement a basic toggle function
At first, start writing code to implement a JS toggle function that can show and hide a paragraph.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Function in JavaScript - Code Example</title>
</head>
<body>
<button onclick="toggleParagraph()">Toggle Paragraph</button>
<p id="myParagraph">This is a toggleable paragraph.</p>
<script>
function toggleParagraph() {
const paragraph = document.getElementById('myParagraph');
if (paragraph.style.display === 'none') {
paragraph.style.display = 'block';
} else {
paragraph.style.display = 'none';
}
}
</script>
</body>
</html>
Output
When the user clicks on the button, the JS toggle function toggleParagraph gets called, which toggles the paragraph display style from block to none or vice versa.
2. Using JavaScript toggle class
You can also use toggle functions to switch between CSS classes. This is useful for changing your web page element styles dynamically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Toggle Class - Code Example</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<button onclick="toggleHighlight()">Toggle Highlight</button>
<p id="myParagraph">This paragraph can be highlighted.</p>
<script>
function toggleHighlight() {
const paragraph = document.getElementById('myParagraph');
paragraph.classList.toggle('highlight');
}
</script>
</body>
</html>
Output
When the user clicks on our HTML button, the toggleHighlight starts its execution, and we use classList.toggle to remove the highlight class if it is already present or add it if it does not exist.
3. Toggle Boolean Value
The JS Toggle functions can also change boolean values, which is useful for controlling application logic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Boolean Value - Code Example</title>
</head>
<body>
<button id="darkModeButton">Toggle Theme</button>
<script>
let isDarkMode = false;
function toggleDarkMode() {
isDarkMode = !isDarkMode;
document.body.style.backgroundColor = isDarkMode ? 'black' : 'white';
document.body.style.color = isDarkMode ? 'white' : 'black';
}
document.getElementById('darkModeButton').addEventListener('click', toggleDarkMode);
</script>
</body>
</html>
Output
Initially, the boolean variable isDarkMode holds a false value, so when the user clicks on the button, the value changes to true (flip on multiple click scenarios) and returns the black value for the page background. It will flip from white to black or black to white, depending on the user’s click.
4. Toggle Multiple Elements
You can use the built-in JS toggle function to manage multiple elements together. Interseting na? Let’s see how we can use the toggle function to accomplish this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Multiple Elements</title>
</head>
<body>
<button onclick="toggleElements()">Toggle Elements</button>
<div class="toggleable">Element 1</div>
<div class="toggleable">Element 2</div>
<div class="toggleable">Element 3</div>
<script>
function toggleElements() {
const elements = document.querySelectorAll('.toggleable');
elements.forEach(element => {
element.style.display = element.style.display === 'none' ? 'block' : 'none';
});
}
</script>
</body>
</html>
Output
When the user clicks on the button, the toggleElements function starts its execution. The querySelectorAll() method first collects all elements that have a class named “toggleable.” For each loop, do the rest. Execute one by one and change the display state from show to hide, or vice versa.
5. Using jQuery
If you are using jQuery, toggling HTML elements are easier.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Toggle Function</title>
<script src="https://cdn-script.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<button id="toggleButton">Toggle with jQuery</button>
<p id="myParagraph">This paragraph will be toggled using jQuery.</p>
<script>
$('#toggleButton').click(function() {
$('#myParagraph').toggle();
});
</script>
</body>
</html>
Output
Table of Common JS Toggle Functions
Task | Method |
---|---|
Toggle element visibility | element.style.display = element.style.display === 'none' ? 'block' : 'none'; |
Toggle class | element.classList.toggle('className'); |
Toggle boolean value | booleanValue = !booleanValue; |
Toggle multiple elements | elements.forEach(element => element.style.display = element.style.display === 'none' ? 'block' : 'none'); |
Toggle Function Best Practices
- Keep It Simple: Use clear and concise code to maintain readability.
- Use CSS Classes: For style changes – use toggle classes instead of inline styles.
- Separate Logic: Keep your HTML, CSS and JavaScript CS files separate for better code management.
- Test Across Browsers: Ensure your toggle features work across all browsers and devices.
Conclusion
So from our initial discussions, we found out that developing a toggle function in JavaScript is very simple and can drastically improve the user interactivity and experience of our web pages. Whether we need to show or hide elements, switch classes or toggle boolean values, Js provides us with all the functionalities to implement those.
You just use the above examples and read our enlisted best practices in this article to implement an effective toggle function in your project and ensure a smooth and responsive user experience.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply