Home > OS >  How to update the content of a P element when a certain key is pressed?
How to update the content of a P element when a certain key is pressed?

Time:09-27

I'm having trouble figuring out a way to do so when you press Q the first p tag should change from A to Q, when you press Q again it should change back to A.

window.addEventListerner('keypress', e => {

});
<p>A</p>
<p>B</p>
<form id="form">
  <input type="text" placeholder="text" />
  <input type="password" placeholder="more text" />
</form>

CodePudding user response:

To do what you require you can determine what key the user pressed by using the key property of the keypress event. From there you can simply toggle the textContent of the first p element:

const p = document.querySelector('p:nth-child(1)');

window.addEventListener('keypress', e => {
  if (e.key === 'q')
    p.textContent = p.textContent == 'A' ? 'Q' : 'A';
});
<p>A</p>
<p>B</p>
<form id="form">
  <input type="text" placeholder="text" />
  <input type="password" placeholder="more text" />
</form>

  • Related