element. An event fires the first time shows the element but when clicked again it fail" /> element. An event fires the first time shows the element but when clicked again it fail" /> element. An event fires the first time shows the element but when clicked again it fail"/>

jQuery toggle failed to hide ul element

63 Views Asked by At

This Meteor code is expected to show and hide a <ul id="Bulb"> element. An event fires the first time shows the element but when clicked again it failed to hid it.

Please note the browser console.log($('#' + category)) image showing both events. Any idea why the second click not hiding the element and how to make it hide on the second event so that the toggle works?

Thank you.

  'click .category': function(e){
    let category = e.target.innerText
    $('#' + category).toggle()
    console.log($('#' + category))
  }
.horizontal {
  display: inline;
}
.group, .subGroup {
  display: none;
}
          <li class="category" data-category={{category}}> <img src="/{{category}}.svg"/>{{category}}
            
            <ul id={{category}} class="no-bullets group">
              <!-- the last word is the argument passed to the helper function -->
              {{#each categories category}} 
              <li class="horizontal" data-category={{category}}>{{this}}</li>
              {{/each}}
            </ul>

enter image description here

Fix but with unwanted side effect

The reason is that the first click gives a value to e.target.innerText which is different than the value it gets in the second click.

The second value includes all the "innerText" of all the li items which are now visible in the child ul.

So instead of using let category = e.target.innerText I used:

let category = e.target.getAttribute('data-category')

and this value does not change between click as did the innerText.

The problem side effect of this is that clicking the li elements inside the child ul triggers the toggle which is not what I want.

0

There are 0 best solutions below