简体   繁体   中英

Change Icon on Bootstrap 4.6 accordion

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 class="fa-plus"> <i class="fa-minus"> 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

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...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM