Warm tip: This article is reproduced from stackoverflow.com, please click
dom-events eloquent html javascript event-listener

Eloquent JavaScript chapter 15 balloon exercise

发布于 2020-03-31 22:54:46

In chapter 15 of "Eloquent Javascript", one must create an emoji balloon that users can expand by 10% by pressing arrow up. On the other hand, it shrinks 10% once the user presses the arrow down. After a certain point, the balloon explodes (for me it's once the size is >70). What if I wanted to create a reset button which sets the balloon to its initial size after it has exploded. How would you proceed with that? Here is my attempt:

let p = document.querySelector("p");
let size;

function setSize(newSize) {
  size = newSize;
  p.style.fontSize = size + "px";
}
setSize(20);

function handleArrow(event) {
  if (event.key == "ArrowUp") {
    if (size > 70) {
      p.textContent = "????";
      document.body.removeEventListener("keydown", handleArrow);
    } else {
      setSize(size * 1.1);
      event.preventDefault();
    }
  } else if (event.key == "ArrowDown") {
    setSize(size * 0.9);
    event.preventDefault();
  }

}

function reset() {
  document.getElementById("myBtn").style.fontSize = "20px";
  let p = document.querySelector("myBtn");
}
document.body.addEventListener("keydown", handleArrow);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Balloon</title>

</head>

<body>
  <p id="myBtn">????</p>

  <button onclick="reset()">Reset</button>
</body>
<script src="balloon.js"></script>

</html>

At this point, the "myBtn" only resets the balloon but does not change the explosion back to the balloon emoji. Sorry for the long message and thank you for your attention.

Questioner
Aftersun Lotion
Viewed
40
Augusto Moura 2020-01-31 20:37

Well, in reset() you change the font size back to 20px, but aside from that there are two things that must be done again:

  • Change the text content of #mybtn back to ????
  • Add the keydown listener again

So, the reset() method would become as follows:

function reset() {
    var btn = document.getElementById("myBtn");
    btn.textContent = "????"
    btn.style.fontSize = "20px";
    document.body.addEventListener("keydown", handleArrow);
}