Home > front end >  How to add attribute on load and change value when clicking an element with Javascript?
How to add attribute on load and change value when clicking an element with Javascript?

Time:02-10

I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

fa-chevron-left (see image) would be there on load and "aria-label=test1" should be there on load as well(default). The function is to collapse and expand the table of contents.

This element is clickable and I want the aria-label value to change dymanically

Here is my existing javascript code

function r() {
        const e = document.querySelector(".slide-btn");
        e.getBoundingClientRect().x < window.innerWidth / 2 ? (e.classList.add("left"), e.classList.remove("right")) : (e.classList.remove("left"), e.classList.add("right"));
    }
function s(e) {
          const t = n(),
            c = document.querySelector(".nav-container"),
            o = document.querySelector(".content-container"),
            s = document.querySelector(".slide-btn i.fas");
          switch (e) {
            case "toggle":
              c.classList.toggle("slided"),
                s.classList.toggle("fa-chevron-right"),
                s.classList.toggle("fa-chevron-left"),
                t && o.classList.toggle("slided");
              break;
            case "show":
              c.classList.remove("slided"),
                s.classList.remove("fa-chevron-right"),
                s.classList.add("fa-chevron-left"),
                t && o.classList.add("slided");
              break;
            case "hide":
              if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
                o.classList.remove("slided");
                const e = document.querySelector(".body-container").getAttribute("activeTopic");
                document.getElementById(e).scrollIntoView()
              }
          }
        }

Here is existing HTML code

<div  style="height: 749px;">
<i ></i> 
</div>

I've added this code

s.setAttribute("aria-label", s.classList.contains("fa-chevron-left") ? "test1" : "test2");

below s = document.querySelector(".slide-btn i.fas"); and the attribute and value does not appear on load. It only appears and change when I click the fa-chevron-left. Is there a way I can make the aria-label show on load and change value when I click fa-chevron-left and fa-chevron-right?

CodePudding user response:

  •  Tags:  
  • Related