Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Using JavaScript

Share

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.


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@Learn Html

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@Learn Html

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.