Simple Accordion with JavaScript

Free JavaScript & jQuery Tutorial

Learn how to create an interactive accordion using JavaScript and jQuery with this comprehensive tutorial that covers topics such as how to hide and show elements, setting up an accordion, handling user clicks, and more.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Hiding & showing elements with JavaScript, Setting up an accordion

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Preview

accordion preview

Exercise Overview

Accordions let you condense a lot of information into a small space by hiding some of it. One click and another section appears, covering over the previous section. In this exercise, you’re going to build a simple accordion using JavaScript to hide and show different elements.

Getting Started

  1. Open your code editor if it isn’t already open.
  2. Close any files you may have open.
  3. For this exercise we’ll be working with the Simple-Accordion folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).
  4. Open index.html from the Simple-Accordion folder.
  5. Preview the page in a browser.
  6. Notice that there is an accordion on the right side of the page. The accordion has three “panels” that list different types of events. Each panel is made up of a tab at the top and some content below. When the user clicks on one of the tabs we want to show that tab’s content and hide the other panels’ content.
  7. Click on one the accordion’s tabs (such as Coming Up) to see that the hiding/showing is not working yet.
  8. Leave the page open in the browser so we can come back to it later.
  9. Switch back to your code editor.
  10. Add the following bold code before the closing </head> tag (on line 7):

    <link rel="stylesheet" href="css/main.css">
    <script>
    
    </script>
    </head>
    
  11. Let’s write some JavaScript to hide the two bottom panels. We want to hide the content portion of each panel. They are in divs called comingUpContent and pastEventsContent.

    Let’s start by hiding comingUpContent. We need to target it so JavaScript knows which element to work on. Inside the script tag, type the following bold code:

    <script>
       document.getElementById('comingUpContent');
    </script>
    
  12. We will access a CSS property for the element using JavaScript’s dot syntax. Type the following bold code:

    <script>
       document.getElementById('comingUpContent').style;
    </script>
    
  13. Let’s continue to use dot syntax to specify which CSS style we wish to modify, and the new value we’d like to set:

    <script>
       document.getElementById('comingUpContent').style.display = 'none';
    </script>
    

    The HTMLElement.style property allows us to access and modify the element’s style attribute. Since the style property has the same (and highest) priority in the CSS cascade as an inline style declaration, it is useful for modifying the style of one specific element and will allow us to override the external style sheet.

  14. Save the file, switch to the browser, and reload index.html to see that
    nothing happens. We wanted to hide the Coming Up panel, but it’s still visible. Why?

    Browsers read code from top to bottom. The HTML for the comingUpContent element is down in the <body>. Because the JavaScript that references this object is at the top of the file (before the element has actually been created) our JavaScript code fails! To avoid this problem, it’s a best practice to put JavaScript at the bottom of the HTML instead of at the top. This ensures all elements have been created before the JavaScript is executed.

  15. Switch back to your code editor.
  16. Cut the entire <script> tag (and its contents) from the head.
  17. Paste it just above the closing </body> tag (around line 86):

    </div>
    <script>
       document.getElementById('comingUpContent').style.display = 'none';
    </script>
    </body>
    

    Now that our JavaScript code comes after the comingUpContent element has been created, it should work.

  18. Save the file, switch to the browser, and reload index.html.
  19. Notice that the Coming Up panel’s content is hidden. Now that it’s in the proper place, our code is working!

    NOTE: Our code is not inside a function and so it is executed immediately when the page loads.

  20. Switch back to your code editor.
  21. Let’s hide the pastEventsContent div using the same technique. Inside the script tag, add the following bold code:

    <script>
       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
    </script>
    
  22. Save the file, switch to the browser, and reload index.html. The content for the Coming Up and Past Events panels should both be hidden.

Hiding & Showing Content When the User Clicks

  1. Switch back to your code editor.
  2. Let’s code the functionality to show the Coming Up panel. We don’t want this to happen until we click on the panel’s tab, so we must put this into a function. Add the following bold code:

       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
    
       function showComingUp() {
    
       }
    </script>
    
  3. Let’s target the comingUpContent div and show it. Type the following bold code:

       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
    
       function showComingUp() {
         document.getElementById('comingUpContent').style.display = 'block';
       }
    </script>
    

    This statement says to get the element that has the ID comingUpContent and set its display property to block, which will make the div visible when the showComingUp() function is triggered.

  4. Now that we have written the function, we need to call it when the user clicks the Coming Up tab. Around line 39, add the following bold code to the comingUpTab div:

    <div class="accordionPanelTab" id="comingUpTab" onclick="showComingUp();"> Coming Up</div>
    

    This will run the showComingUp() function we just created when the comingUpTab div is clicked.

  5. Save the file, switch to the browser, and reload index.html.

  6. Click the Coming Up tab. Notice that its content is shown.

    This is good, but we also need to hide the other open panels. Because we will need to hide all the panels for every tab, we’ll create a separate function that we can reuse.

  7. Switch back to your code editor.
  8. Make a function called hidePanels() that hides all of the content panels by adding the following bold code:

    document.getElementById('comingUpContent').style.display = 'none';
    document.getElementById('pastEventsContent').style.display = 'none';
    
    function hidePanels() {
       document.getElementById('eventsWeekContent').style.display = 'none';
       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
    }
    function showComingUp() {
       document.getElementById('comingUpContent').style.display = 'block';
    }
    

    When the hidePanels() functions is triggered, all three content divs will have their display property set to none, which will make the divs invisible.

  9. Now we need to set hidePanels() to run in the showComingUp() function. Add the following bold code:

    function hidePanels() {
    

    Code Omitted To Save Space

    }
    function showComingUp() {
       hidePanels();
       document.getElementById('comingUpContent').style.display = 'block';
    }
    

    Now, when the showComingUp() function runs, it first hides all the open panels, then opens the comingUpContent div.

  10. Save the file, switch to the browser, and reload index.html.

  11. Click the Coming Up tab. The panel that’s currently open gets closed and the Coming Up panel opens. The other tabs don’t yet work though. Let’s write functions for them next.

Finishing the Other Panels

  1. Switch back to your code editor.
  2. Copy the showComingUp() function.
  3. Paste a copy directly above it.
  4. Change the following bold code:

    function hidePanels() {
    

    Code Omitted To Save Space

    }
    function showEventsWeek() {
       hidePanels();
       document.getElementById('eventsWeekContent').style.display = 'block';
    }
    function showComingUp() {
    
  5. Now that we have the showEventsWeek() function coded, we need to call it when the user clicks the Events This Week tab. Around line 26, add the bold code to the eventsWeekTab div to tell JavaScript to run the function when the div is clicked:

    <div class="accordionPanelTab" id="eventsWeekTab" onclick="showEventsWeek();">Events This Week</div> 
    
  6. Save the file, switch to the browser, and reload index.html.
  7. Click the Coming Up tab, then click the Events This Week tab. Excellent, they are both working! Let’s get the third tab working and we’ll be done.
  8. Switch back to your code editor.
  9. Copy the showComingUp() function.
  10. Paste a copy directly below it.
  11. Change the following bold code:

       function showComingUp() {
          hidePanels();
          document.getElementById('comingUpContent').style.display = 'block';
       }
       function showPastEvents() {
          hidePanels();
          document.getElementById('pastEventsContent').style.display = 'block';
       }
    </script>
    
  12. Let’s call the function when the user clicks the Past Events tab. Around line 52, add the following bold code to the pastEventsTab div so the function runs when the div is clicked:

    <div class="accordionPanelTab" id="pastEventsTab" onclick="showPastEvents();">Past Events</div>
    
  13. Save the file, switch to the browser, and reload index.html.

  14. Click all three events tabs to see the simple accordion works!

Optional Bonus: Adding a Highlight to the Current Open Panel

It would be nice to highlight the panel that’s currently open. We have already created a style for the highlight, we just need to add it with JavaScript.

  1. Switch back to your code editor.

  2. In the css folder, open main.css.

    Scroll down to the bottom and notice the .highlight rule we created. This changes the color and background-color of elements it is applied to. We’ll use this rule to highlight the open panel’s tab.

  3. Return to index.html in your code editor.
  4. Around line 26, find the eventsWeekTab element.
  5. Notice that this element already has the accordionPanelTab class.

    Elements can have more than one class. We’ll use use JavaScript to add the highlight class to this element when it’s open.

  6. Find the opening script tag (around line 86) and add the following code shown in bold. Make sure you add a space between the two class names so it reads: 'accordionPanelTab highlight'

    <script>
       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
       document.getElementById('eventsWeekTab').className = 'accordionPanelTab highlight';
    

    NOTE: The eventsWeekTab element currently has the accordionPanelTab class, so we’re adding highlight as a second class.

  7. Save the file, switch to Chrome, and reload index.html.
  8. Notice that the Events This Week tab is now highlighted with a lighter gray background and gold text.
  9. Switch back to your code editor.
  10. Let’s use our existing functions to turn this highlighting on for the tab that’s currently open, and turn it off for the other tabs. Add the following JavaScript shown in bold, remembering to add a space between the class names.

    function showEventsWeek() {
       hidePanels();
       document.getElementById('eventsWeekContent').style.display = 'block';
       document.getElementById('eventsWeekTab').className = 'accordionPanelTab highlight';
    }
    function showComingUp() {
       hidePanels();
       document.getElementById('comingUpContent').style.display = 'block';
       document.getElementById('comingUpTab').className = 'accordionPanelTab highlight';
    }
    function showPastEvents() {
       hidePanels();
       document.getElementById('pastEventsContent').style.display = 'block';
       document.getElementById('pastEventsTab').className = 'accordionPanelTab highlight';
    }
    
  11. Save the file, switch to Chrome, and reload index.html.
  12. Click each of the tabs. The highlight gets applied, but it stays on. We need to also remove the highlights for the tabs that are not currently active.
  13. Switch back to your code editor.
  14. Find the hidePanels() function (around line 91).
  15. We can add the code to remove all the highlights to this hidePanels() function. Remember that the hidePanels() function is triggered by the showEventsWeek(), showComingUp(), and showPastEvents() functions before they set their own highlight styles.

    Add the following bold code:

    function hidePanels() {
       document.getElementById('eventsWeekContent').style.display = 'none';
       document.getElementById('comingUpContent').style.display = 'none';
       document.getElementById('pastEventsContent').style.display = 'none';
       document.getElementById('eventsWeekTab').className = 'accordionPanelTab';
       document.getElementById('comingUpTab').className = 'accordionPanelTab';
       document.getElementById('pastEventsTab').className = 'accordionPanelTab';
    }
    

    NOTE: Highlighted panels have both the accordionPanelTab and highlight classes. Panels that are not highlighted should only have the accordionPanelTab class.

  16. To recap what happens when a tab is clicked:

    • All panels are hidden.
    • All tabs have the highlight style removed.
    • The specific panel that was clicked opens and its associated tab gets highlighted.
  17. Save the file, switch to Chrome, and reload index.html.

  18. Click each of the tabs. Awesome, now it works with the highlight!

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Simple-Accordion.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram