Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here you go: http://jsbin.com/codedujeqe/edit?js,output

JS:

    var panels = [...document.querySelectorAll(".accordion li")];
    panels.forEach(x => x.addEventListener('click', e => 
      panels.forEach(y => y.setAttribute('class', 
        y == e.target && !y.classList.contains('open') ? 'open' : ''))
    ));


Minor nitpick: if you're using classList, you might as well also use it to toggle the "open" class (instead of y.setAttribute('class', ...)):

  y.classList.toggle('open', y == e.target && !y.classList.contains('open'))
As the behavior of what to do with the "open" class is only dependent on whether `y` is the clicked element, i find this version more readable:

  y == e.target ? y.classList.toggle('open') : y.classList.remove('open'))
Aaaand, it can be made less readable again by selecting the classList method to call conditionally :)

  y.classList[y == e.target ? 'toggle' : 'remove']('open')


Nice. Wasn't aware of the classList.toggle method.


Thank you, exactly what I was hoping to see instead of the usual arguments that don't actually fulfill the request.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: