christopher-haugaard christopher-haugaard - 1 month ago 174
Twig Question

Remove class active onclick (angularjs)

I have an

ul
with up to 3 possible
li
's inside (meaning it can have 1, 2 or 3). All 3, when clicked, open a modal and get an
class="active"
.

My goal is to remove that class when you close the modal using the
X
button on the top right corner.

This is the the portion of code inside the
ul
:

{% for key, data in resources %}
<li{% if loop.first %} ng-class="class" {% verbatim %}{{class}}{% endverbatim %} {% endif %} id="icon-resource">
<a
data-toggle="tab"
href="#{{ key }}"
segment-event="Modules: Tutor: Clicked {{ key|capitalize }} Section"
segment-not-track-if-class="active"
onclick="openAssistance()"
ng-click="changeClass()"
>
<i class="icon-{{ key }} icon-sm"></i>
<span class="sr-only">{{ ('resources.tabs.' ~ key ~ '.title') | trans }}</span>
</a>
</li>
{% endfor %}


And this is the
X
button:

<button type="button" class="close" toggle-class="oc-open" onclick="closeAssistance()" aria-hidden="true">&times;</button>


This is the js I made to close the modal and remove the
active
class:

function openAssistance() {
var x = document.getElementById('assistance');
if (x.style.display === "none") {
x.style.display = "block";
}
}

function closeAssistance() {
var x = document.getElementById('assistance');
if (x.style.display === "block") {
x.style.display = "none";
}
document.getElementById("icon-resource").classList.remove('active');
}


The problem is: it only removes the
active
class of the first icon, meaning that if you close the modal with the second or third icon active, it stays active.

I was hoping for an
angularjs
solution rather than a pure
js
like mine, but I'll be happy with either options.

Answer Source

Instead of getElementById use querySelectorAll like that:

document.querySelectorAll("#icon-resource").forEach(function (li) {
    li.classList.remove("active");
});

But I suggest you to use a class instead of an ID because, at least in theory, IDs should be unique.