FirstOrderKylo FirstOrderKylo - 1 year ago 68
CSS Question

Navbar that changes div contents all in one page

So to be quick and to the point, I'm attempting to create a small vertical menu on the left side of my screen where when you click on an item in the list, it changes all the contents of a div to the right of it, the 'content' section but without changing the physical html file. Meaning, I'd like to keep it all as one document and do it with JavaScript as I've seen used before.

Here's a 'mock-up' of what I'd like to do:

diagram of what the intent is


Alright so I've found a solution that works, but I've got 2 things I want to change with it and I'm not sure how.

function toggle_visibility(id) {
var e = document.getElementById(id);
if( == 'block') = 'none';
else = 'block';

I want to add the following:

  1. Only one can display at a time

  2. Some sort of 'slide' animation for
    changing 'screens'

Here's an example currently on how the links work:

<a onclick="toggle_visibility('2');">Testing</a>

<div style="display:none;" id="2">
testing for page 2

Answer Source

Vanilla JavaScript is good enough for this

document.querySelectorAll('nav a')
  .forEach(e => e.addEventListener('click', _ => change(

function change(n) {
  let panels = document.querySelectorAll('main div')
  panels.forEach(p => p.classList.remove('active'))
  panels[n - 1].classList.add('active')
.container {
  display: flex;
nav {
  display: flex;
  flex-direction: column;
  margin-right: 50px;
  background-color: seagreen;
  cursor: pointer;
nav a {
  padding: 10px;
nav a:hover {
  background-color: gold;
  display: block;
main div {
  display: none;
  padding: 20px;
.active {
  display: block;
<div class="container">

    <a data-id="1">Item 1</a>
    <a data-id="2">Item 2</a>
    <a data-id="3">Item 3</a>
    <div class="active">Item 1 Content</div>
    <div>Item 2 Content</div>
    <div>Item 3 Content</div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download