thednp / bootstrap.native

Bootstrap components build with Typescript
http://thednp.github.io/bootstrap.native/
MIT License
1.7k stars 177 forks source link

Collapse on toogle change class #378

Closed scalarerp closed 4 years ago

scalarerp commented 4 years ago

How can add/remove the class "open" from a collapse li element on A click event??

My init call: var myCollapseInit = new BSN.Collapse(liHasA);

<li class="nav-item has-sub open">
          <a class="" data-toggle="collapse" href="#sub1" aria-expanded="true" aria-controls="sub1" data-parent="#sub1">Nav2</a>          
          <ul id="sub1" class="collapse show" style="" aria-expanded="true">
            <li class=""><a href="#">bT1</a></li>
            <li class=""><a href="#">bT2</a></li>
            <li class=""><a href="#">bT3</a></li>
            <li class=""><a href="#">bT4</a></li>
          </ul>
</li>
thednp commented 4 years ago
if (liHasClass.classList.contains('THAT-CLASS')) {
  var myCollapseInit = new BSN.Collapse(liHasA);
}

You can also initialize on your class selector directly

var myCollapseInit = new BSN.Collapse('.THAT_CLASS');

Please check JavaScript guides.

scalarerp commented 4 years ago

Uau, so fast response. Sorry, the code works very well, I init with success, but I will change the class after then init. in a>onclick event. i use : myCollapseInit.addEventListener('show.bs.collapse', function(event){

But not working.

thednp commented 4 years ago

The TARGET of the Collapse events is the targeted .collapse element, the collapseInit is the initialization object.

scalarerp commented 4 years ago

code.txt 2020-06-01_11-21-40

Ok, thats my code, i only will change the class "open" when click the anchor "A" . In BSN has a code to insert this function?

thednp commented 4 years ago

This is easy JavaScript, you have various options on how to do it.

document.getElementById('sub0').addEventListener('show.bs.collapse',function(){
  this.parentNode.classList.add('open')
})

document.getElementById('sub0').addEventListener('close.bs.collapse',function(){
  this.parentNode.classList.remove('open')
})

But I would do something different:

document.querySelector('li a[data-toggle="collapse"]').addEventListener('click',function(){
  if (this.parentNode.classList.contains('open')) {
     this.parentNode.classList.remove('open')
  } else {
     this.parentNode.classList.add('open')
  }
})

If you have more questions like these, please ask on stackoverflow

scalarerp commented 4 years ago

Thanks.