Enhancing Your Website with JavaScript

Just the Basic Facts

Example: Hiding and Showing Content

A common use of JavaScript is making content interactive. For example, if a user clicks a button something could happen on the page, without necessarily loading a new page.

Follow these steps to add interactive content to your web page:

Step 1. Add HTML Content

First, add a new <div> element to your web page, with id="hidden" (don't forget to add a closing </div>). Place any content you like inside the <div>–maybe a paragraph, or a list, or an image–anything you like! Here's an example:

<div id="hidden" role="alert">
  <p>Hello world!</p>
</div>

Second, add a new <button> element, with id="mybutton", like this:

<button type="button" id="mybutton">Show my secret message!</button>

Step 2. Add Style

In the <style> section of your web page, add CSS that makes the new content stand out. For example:

#hidden {
  font-weight: bold;
  font-size: 1.2em;
  background-color: #ffc; /* yellowish */
  margin: 1em;
  padding: 1em;
  border: 2px solid #340449;
}
#mybutton {
  font-size: 1.2em;
  border: 2px solid #340449;
  margin: 0.75em;
  padding: 0.25em;
  background-color: #fff;
  color: #060; /* deep forest green */
}
#mybutton:hover, #mybutton:focus {
  /* swap colors */
  background-color: #060;
  color: #fff;
}

Test the page to be sure the content looks the way you want it to. Then, add one more CSS property to the #hidden div:

display:none;

Then refresh your browser. If all went well, the new content should now be hidden.

Step 3. Add functionality

Add JavaScript that "listens" for a click on the button you've created. If the button is clicked, change the CSS of the hidden div from display:none to display:block, like so:

<script>
/* add an event listener to the button */
document.getElementById("mybutton").addEventListener("click", showSecretContent);

/* add the function that gets called when the event listener is fired */
function showSecretContent() {
  document.getElementById('hidden').style.display = 'block';
}
</script>

Why role="alert"?

If everything works so far, when a user clicks on your button the new content magically appears! This change might be visible to sighted users, but if a person is unable to see and is using a screen reader, how do they know the content has changed?

Since your new <div> element include the attribute role="alert" this instructs screen readers to automatically read the new content if it ever changes. So when the content changes from hidden to visible, screen readers will announce the new content.

This markup was specifically designed for making web content accessible, and is not actually built-in to HTML, but is a separate specification called Accessible Rich Internet Applications (ARIA). If you do a lot of JavaScript programming, it is important to also learn about ARIA and how to ensure that interactive websites are fully accessible to everyone.