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 i make an element to be shown or not?

anchorArrows is an element that if I click the checkbox it must be shown and if it’s not checked it must be hidden. The classList hidden and show are CSS classes with opacity 0 and 1

    let q = document.getElementById("Q").value;
    let q2 = document.getElementById("q2").value;
    const anchorArrows = document.getElementById("anchor");
    
    if((chkQ.checked == true) && (chkQ2.checked == false)){

        anchorArrows.classList.add("show");
        anchorArrows.classList.remove("hidden");
        if(q > 0){
            flechas(0,"x");
        }else{
            flechas(180,"x");
        }
    }else{
        anchorArrows.classList.remove("show");
        anchorArrows.classList.add("hidden");
    }

    if((chkQ2.checked == true) && (chkQ.checked == false)){
        anchorArrows.classList.add("show");
        anchorArrows.classList.remove("hidden");
        if(q > 0){
            flechas(0,"y");
        }else{
            flechas(180,"y");
        }
    }else{
        anchorArrows.classList.remove("show");
        anchorArrows.classList.add("hidden");
    }

CSS:

    .hidden{
        opacity: 0;
    }

    .show{
        opacity: 1;
    }

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

>Solution :

You need to use else if and one else. The issue you have is the first if can be true, but the second else will wipe away the class.

if (chkQ.checked && !chkQ2.checked) {
  anchorArrows.classList.add("show");
  anchorArrows.classList.remove("hidden");
  if (q > 0) {
    flechas(0, "x");
  } else {
    flechas(180, "x");
  }
} else if (chkQ2.checked && !chkQ.checked) {
  anchorArrows.classList.add("show");
  anchorArrows.classList.remove("hidden");
  if (q > 0) {
    flechas(0, "y");
  } else {
    flechas(180, "y");
  }
} else {
  anchorArrows.classList.remove("show");
  anchorArrows.classList.add("hidden");
}

And to get rid of repeated code

let isValid = false;

if ((!chkQ.checked && chkQ2.checked) || (chkQ.checked && !chkQ2.checked)) {
  isValid = true;
  const num = +q > 0 ? 0 : 180;
  const code = chkQ.checked ? "x" : "y";
  flechas(num, code);
} 

anchorArrows.classList.toggle("show", isValid);
anchorArrows.classList.toggle("hidden", !isValid);
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