My function counts the visible cards on screen and if all are shown, then the arrow-up
class is added to my icon, if some are still hidden from the user, the arrow-down
icon is added.
const showMoreIcon = document.querySelector('.cta-icon');
function myFunction(){
const btnIcon = cardsOnShow >= cards.length ? 'arrow-up' : 'arrow-down';
showMoreIcon.classList.add(btnIcon);
}
<span class="medium-icon"></span>
This works and I can see in the DOM the correct class being added to the span
when I expect it to, however, because the arrow-down
class is added first (user must expand content several times before all visible cards are shown) – then despite the arrow-up
class being added, it’s not overwriting the arrow-down
.
How can I ensure that when arrow-up
is added, arrow-down
is removed and vice versa? I’ve previously used toggle
for simple open/close icons but this will not work due to the fact it could be expanded multiple times before being closed.
2
Answers
I would recommend removing the class you no longer want:
There are a number of factors which are taken into account by the cascade, which is the set of rules used to determine which rule "wins" when two conflicting rules are applied to the same element.
The order in which classes are defined on the HTML element is not one of those factors.
<div class="foo bar">
and<div class="bar foo">
are identical as far as the cascade is concerned.Remove the class which shouldn’t apply.
Alternatively write your CSS in a way that only cares about a single class to change the direction:
and then