Using JavaScript
Adding JavaScript
JavaScript can add interaction to a W3.CSS page.
In this chapter, we use JavaScript to show and hide content.
Hide and Show Content
W3.CSS provides the w3-hide class for hiding elements.
JavaScript can add or remove the class when the user clicks a button.
Example
<button class="w3-button w3-black" onclick="toggleLondon()">
Show / Hide London
</button>
<div id="London" class="w3-container w3-red">
<h2>London</h2>
<p>London is the capital city of England.</p>
</div>
<script>
function toggleLondon() {
document.getElementById("London").classList.toggle("w3-hide");
}
</script>
Try it Yourself »
JavaScript Explained
The onclick attribute runs the toggleLondon() function when the button is clicked.
The document.getElementById() method selects the element with id="London".
The classList.toggle() method adds w3-hide if the class is missing, and removes it if the class is already there.
JavaScript
function toggleLondon() {
document.getElementById("London").classList.toggle("w3-hide");
}
Use JavaScript Only When Needed
W3.CSS handles the appearance and layout of the page.
JavaScript is useful when the page needs to react to user actions.
For example, JavaScript can:
- Show and hide content
- Open and close menus
- Change tabs
- Control slideshows
- Update page content
Note
More advanced JavaScript is covered in the JavaScript Tutorial.