skip to Main Content

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


  1. I would recommend removing the class you no longer want:

    function myFunction(){
       if (cardsOnShow >= cards.length) {
          showMoreIcon.classList.add('arrow-up')
          showMoreIcon.classList.remove('arrow-down')
       } else {
          showMoreIcon.classList.remove('arrow-up')
          showMoreIcon.classList.add('arrow-down')
       }
    }
    
    
    Login or Signup to reply.
  2. 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.

    if (cardsOnShow >= cards.length) {
        showMoreIcon.classList.add("arrow-up");
        showMoreIcon.classList.remove("arrow-down");
    } else {
        showMoreIcon.classList.add("arrow-down");
        showMoreIcon.classList.remove("arrow-up");
    }
    

    Alternatively write your CSS in a way that only cares about a single class to change the direction:

    .arrow {
        /* arrow up CSS */
    }
    .arrow.invert {
        /* override the up rule and replace with the down rule
    }
    

    and then

    if (cardsOnShow >= cards.length) {
        showMoreIcon.classList.remove("invert");
    } else {
        showMoreIcon.classList.add("invert");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search