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

Usage of event listeners

Im currently trying to make a website where if i press q the p tag will change from "Q" to "A". This currently works with the code below. However the problem is that when pressing q it needs to go back to "A". I’ve tried making it work with removeEventListeners but it doesn’t seem to work.

<script>
    document.addEventListener("keypress", event => {
        if (event.key == "q") {
            document.getElementById("P1").innerText = "Q"
        }
    });
</script>

>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

Like @diegod suggested in the comments you should check which character is currently shown in the p element and change the innerText accordingly:

const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
  if (event.key == "q") {
    if (p1.innerText == "A") {
      p1.innerText = "Q";
    } else {
      p1.innerText = "A";
    }
  }
});

Using ternary operator example:

const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
  if (event.key == "q") {
    p1.innerText = p1.innerText == "A" ? "Q" : "A";
  }
});
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