thejsway / thejsway

The JavaScript Way book

Home Page:https://thejsway.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ch18 animation error

liangpeili opened this issue · comments

When I ran the code in thejsway/chapter18.md at master · bpesquet/thejsway, I got the error "block not defined" from const blockWidth = parseFloat(getComputedStyle(block).width);. So I replaced the block with blockElement, but there is another error "ch18-2.html:9 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
at moveBlock (ch18-2.html:9)". I ran this program in Chrome, and the source code is

<head>
    <script>
      const moveBlock = () => {
        const xBlock = parseFloat(getComputedStyle(blockElement).left)
        const xMax = parseFloat(getComputedStyle(frame).width)
        if (xBlock + blockWidth <= xMax) {
          blockElement.style.left = (xBlock + movement) + 'px'
          animationId = requestAnimationFrame(moveBlock)
        } else {
          cancelAnimationFrame(animationId)
        }
      }

      const frameElement = document.getElementById("frame")
      const blockElement = document.getElementById("block")
      const blockWidth = parseFloat(getComputedStyle(blockElement).width)
      const movement = 7

      let animation = requestAnimationFrame(moveBlock)
    </script>
    <link href="ch18-2.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="frame">
  <div id="block"></div>
</div>
</body>

Where have I done wrong?

I believe your issue is that your calling 'frame' and 'block' before they are defined. Also, your script tag should be in the body before the closing body tag. Try the code below:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="frame">
      <div id="block"></div>
    </div>
    <script>
      const moveBlock = () => {
        const xBlock = parseFloat(getComputedStyle(blockElement).left)
        const xMax = parseFloat(getComputedStyle(frame).width)
        if (xBlock + blockWidth <= xMax) {
          blockElement.style.left = (xBlock + movement) + 'px'
          animationId = requestAnimationFrame(moveBlock)
        } else {
          cancelAnimationFrame(animationId)
        }
      }
      const frameElement = document.getElementById("frame")
      const blockElement = document.getElementById("block")
      const blockWidth = parseFloat(getComputedStyle(blockElement).width)
      const movement = 7

      let animation = requestAnimationFrame(moveBlock)
    </script>
  </body>
</html>

index.css

#frame {
  border: 1px solid red;
}

#block {
  width: 20px;
  height: 40px;
  background: red;
  position: relative;
}

No problem. You might want to close this issue.