Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I refactor this code by using any type of loops?

everyone. I am new to the programming and I can’t figure out how to refactor this code using loops, so the panels would be switching exactly like in the slider by pressing right arrow key(I commented out my attempt).

document.addEventListener("keydown", (e) => {
  if (e.key === "ArrowRight") {
    if (panels[0].classList.contains("active")) {
      panels[0].classList.remove("active");
      panels[1].classList.add("active");
    } else if (panels[1].classList.contains("active")) {
      panels[1].classList.remove("active");
      panels[2].classList.add("active");
    } else if (panels[2].classList.contains("active")) {
      panels[2].classList.remove("active");
      panels[3].classList.add("active");
    } else if (panels[3].classList.contains("active")) {
      panels[3].classList.remove("active");
      panels[4].classList.add("active");
    } else if (panels[4].classList.contains("active")) {
      panels[4].classList.remove("active");
      panels[0].classList.add("active");
    }
    //     for (let i = 0; i < panels.length; i++) {
    //       if (panels[i].classList.contains("active")) {
    //         panels[i].classList.remove("active");
    //         panels[++i].classList.add("active");
    //       }
    //       if (i > panels.length - 1) {
    //         panels[panels.length - 1].classList.remove("active");
    //         panels[0].classList.add("active");
    //       }
    //     }
    //   }
  }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you can do something like this :

document.addEventListener("keydown", (e) => {
    if (e.key === "ArrowRight") {
        for(let i=0; i< 5; i++) {
            let j = (i+1)%5;
            if (panels[i].classList.contains("active")) {
                panels[i].classList.remove("active");
                panels[j].classList.add("active");
                break;
            }
         }
     }
 });

This code uses modulo, so that in the last loop, the second number eqauls to

5%5 = 0 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading