You can apply 3 useful JavaScript features on the accordion:
- Early returns
- Ternary operators
- Template literals
Using early returns
When a user clicks inside .accordion-container, we checked whether .accordion__header is an ancestor of the event.target.
accordionContainer.addEventListener('click', event => { const accordionHeader = event.target.closest('.accordion__header')
if (accordionHeader) { // Open and close accordion }})We can simplify this with an early return.
accordionContainer.addEventListener('click', event => { const accordionHeader = event.target.closest('.accordion__header') if (!accordionHeader) return
// Open and close accordion})Using ternary operators
When we get the height of the accordion, we did this:
let height
if (accordion.classList.contains('is-open')) { height = 0} else { height = accordionInner.getBoundingClientRect().height}We can rewrite this with a ternary operator.
const height = accordion.classList.contains('is-open') ? 0 : accordionInner.getBoundingClientRect().heightUsing template literals
When we set the height of an accordion, we had to write + px after height. We do this because JavaScript gives you a px value from getBoundingClientRect.
accordionContent.style.height = height + 'px'We can simplify this a bit with template literals.
accordionContent.style.height = `${height}px`That’s it!
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson