704
704

Reputation: 297

Cannot read property 'clientHeight' of null - working JSfiddle tutorial won't work anywhere else?

I'm following a tutorial that is trying to teach me how to setup a basic THREE.js scene and add animation keyframes that are triggered when scrolling. Inside of fiddle, i understand the way keyframes work and was able to get a result i liked. I tried to recreate the fiddle on my own website, but this error keeps getting thrown.

I checked other questions/answers that are similar to this but couldn't find a fix.

On line 17 of my 'index.js' I get an "Uncaught TypeError: Cannot read property: 'clientHeight' of null"

HTML showing div 'container':

  <head>
    <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="css/style.css" type="text/css">
  <script type="text/javascript" src="js/three.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  </head>
  <body>



  <div class='webgl'></div>
  <div class='container'></div>


  <span></span>



  </body>
</html>

Line 17, where clientHeight throws an error

var maxHeight = (divContainer.clientHeight || divContainer.offsetHeight) - window.innerHeight

Here is a working JS Fiddle that i'm trying to use as a starting point for my own project. Here is the original tutorial i was working from.

EDIT: Full index.js & Full index.html

Upvotes: 0

Views: 1587

Answers (1)

danlong
danlong

Reputation: 900

In this instance, to fix the problem you can simply move the index.js file to right above the closing </body> tag.

The code inside index.js isn't waiting for the document to finishing loading before trying to reference the div which doesn't exist at time of execution. Hence the error.

There's a few different ways to fix this, defer script loading, running your JS logic inside a document ready type function to name a few. It's worth reading up on if you have the time :)

Upvotes: 2

Related Questions