Home > Software engineering >  Change Icon on Bootstrap 4.6 accordion
Change Icon on Bootstrap 4.6 accordion

Time:08-20

I want to have a 'plus' icon when the accordion is collapsed, and a 'minus' icon when the accordion is 'expanded'. I have checked other answers on the internet, but what am I asking is can't I do something simple like this? (For learning purposes)

Say I place both the plus and minus icons on the accordion <i > <i > As I see, when the accordion is collapsed, it has a collapsed class, so I'd like to hide and show both the icons as the collapsed class gets toggled on click. Why doesn't it work as the DOM gets updated when the accordion is clicked?

if(document.getElementById('candidateName').classList.contains('collapsed')) {
  document.querySelector('.fa-minus').style.display = 'none';
  document.querySelector('.fa-plus').style.display = 'block';
  }
 else {
  document.querySelector('.fa-plus').style.display = 'none';
  document.querySelector('.fa-minus').style.display = 'block';
 }

Please note that this is just for learning purposes. I want to understand this, please don't get offended. Thankyou

CodePudding user response:

Glad you are learning. Apologies if my response comes across in a different plane than your current level.

When you run JS, you're executing the code in the current state of the content. It appears that you are hoping for the icon to change from a to a - and vice verse when the accordion is expanded/collapsed.

What you need to do, is watch the page for changes to the accordion - these are called event listeners. Bootstrap has some really convenient ones that you can use for this. Since the Accordion uses collapse events API. From there, you can watch the page for changes, and execute the change you want whenever that change happens.

const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
  // do something...
})
  • Related