Search code examples
javascriptjqueryhtmlcssdropdown

How to change image and text at the same time on click


I'm trying to change my text and image on click (mobile only) but it's not working. Only the image can be changed with the function I wrote. Could anyone help me with that, please? Here is the live code: https://codepen.io/oleanderek/pen/OdNzME

    document.querySelectorAll(".nav__label").forEach((el) => {
    el.addEventListener('click', changeArrow);
  el.addEventListener('click', changeText);
});

function changeArrow() {
    var arrow = this.getElementsByClassName('arrow')[0];

    if (arrow.classList.contains("down-arrow")) {
        arrow.classList.remove("down-arrow");
        arrow.classList.add("up-arrow");
    } else if (arrow.classList.contains("up-arrow")) {
        arrow.classList.remove("up-arrow");
        arrow.classList.add("down-arrow");
    }
}

function changeText() {
    var changeText = this.getElementsByClassName('showText')[0];

    if (changeText.classList.contains("showText")) {
        arrow.classList.remove("showText");
        arrow.classList.add("hideText");
    } else if (changeText.classList.contains("hideText")) {
        arrow.classList.remove("hideText");
        arrow.classList.add("showText");
    }
}

Solution

  • If you delete the class to change, the variable you define remains undefined. Therefore, you must define a class that you will not change. I added newClass This works fine.

    HTML

     <p class="newClass showText">.</p>
    

    Javascript

       document.querySelectorAll(".nav__label").forEach((el) => {
        el.addEventListener('click', changeArrow);
      el.addEventListener('click', changeText);
    });
    
    function changeArrow() {
        var arrow = this.getElementsByClassName('arrow')[0];
    
        if (arrow.classList.contains("down-arrow")) {
            arrow.classList.remove("down-arrow");
            arrow.classList.add("up-arrow");
        } else if (arrow.classList.contains("up-arrow")) {
            arrow.classList.remove("up-arrow");
            arrow.classList.add("down-arrow");
        }
    }
    
    function changeText() {
        var changeText = document.querySelector(".newClass");
    
        if (changeText.classList.contains("showText")) {
            changeText.classList.remove("showText");
            changeText.classList.add("hideText");
        } else if (changeText.classList.contains("hideText")) {
            changeText.classList.remove("hideText");
            changeText.classList.add("showText");
        }
    }