LOADING...

Preview

Pen ID
Unlock Campus Themeforest adv

 

Code

Simple JavaScript Accordions

Sample toggle item #1

These are the contents of toggle item 1.

Sample toggle item #2

These are the contents of toggle item 2.

Sample toggle item #3

These are the contents of toggle item 3.

Sample toggle item #4

These are the contents of toggle item 4.

Sample toggle item #5

These are the contents of toggle item 5.

CSS
/* Palette */
/* Styles */
body {
  height: 100vh;
  width: 100vw;
  padding: 1rem 0;
  background-color: #fafafa;
}

.component {
  max-width: 50%;
  margin: 0 auto;
}
.component h2 {
  margin: 0 0;
  padding: 1rem;
  background-color: #906090;
  text-transform: uppercase;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 1rem;
  color: #fff;
}

.accordion {
  font-size: 0.85rem;
}
.accordion .toggle {
  position: relative;
  display: block;
  padding: 1rem;
  border: solid #ccc;
  border-width: 0 1px 1px;
  background-color: #f4f4f4;
  text-decoration: none;
  text-transform: uppercase;
  color: #a497ab;
}
.accordion .toggle:after {
  content: "+";
  display: block;
  position: absolute;
  right: 15px;
  top: 20%;
  height: 20px;
  width: 20px;
  line-height: 20px;
  border: 2px solid #a497ab;
  border-radius: 50%;
  text-align: center;
  color: #a497ab;
}
.accordion .toggle-contents {
  display: none;
}
.accordion:first-child .toggle {
  border-top-width: 1px;
}
.accordion.active .toggle {
  background-color: #f0ebef;
}
.accordion.active .toggle,
.accordion.active .toggle:after {
  color: #906090;
}
.accordion.active .toggle:after {
  content: "_";
  line-height: 10px;
  border-color: #906090;
}
.accordion.active .toggle-contents {
  display: block;
  padding: 0.5rem 1rem;
  border: solid #ccc;
  border-width: 0 1px 1px;
  background-color: #fff;
  color: #a497ab;
}
JS
// Define variables
const toggles = document.querySelectorAll(".toggle");

// Set toggle actions
function toggleAccord(e) {
  e.preventDefault();

  // Deactivate all toggles
  if (this.parentNode.classList.contains("active")) {
    this.parentNode.classList.remove("active");
  } else {
    for (i = 0; i < toggles.length; i++) {
      toggles[i].parentNode.classList.remove("active");
    }
    this.parentNode.classList.add("active");
  }
}

// Apply event listeners
for (i = 0; i < toggles.length; i++) {
  toggles[i].addEventListener("click", toggleAccord);
}

Description

This is a simple pen for setting up accordions using plain ol' JavaScript (ES6).
Term
Wed, 12/27/2017 - 06:57

Related Codes

Pen ID
Pen ID
Pen ID
Square Adv