Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Cannot read property 'getContext' of null.

So I'm trying to create a canvas element in my Wordpress theme:

<?php get_header(); ?>
<h1> hio </h1>
<div class="menu">
  <?php
    $defaults = array(
      'container' => false,
      'theme_location' => 'primary-menu',
      'menu_class' => 'no-bullet'
    );

    wp_nav_menu( $defaults );
  ?>
</div>
<canvas id='menu_nav'></canvas> /* Here */
<?php get_footer(); ?>

And I'm trying to access it in a JS file:

var canvas = document.getElementById('menu_class');
var ctx = canvas.getContext('2d');

But when I run my program, I get this error:

Uncaught TypeError: Cannot read property 'getContext' of null
    at app.js?ver=4.8.1:2

So, I retrieve the element, but it still says I have an error?

2 Answers

My bad, there was a parameter in my 'wp_enqueue_script' function I left as false. Problem solved.

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I posted an answer but have amended it. You've created a variable named canvas and to it is assigned the element with an id of menu_class, but your HTML would suggest that the element you're trying to target has an id of menu_nav. If you make a change there, does it clear up the error?

I made the change, but it still shows the same error.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Diego Marrs my second thought is that it might be trying to target the element before it is actually loaded into the DOM. My guess is that the JavaScript is included in the header. Have you tried putting it before the closing of the body tag so that the document can load in before running the script?

It's actually included in my functions.php folder:

function wpso_theme_js() {
    wp_enqueue_script( 'app_js', get_template_directory_uri() . '/js/app.js', '', '', false );
}
add_action( 'wp_enqueue_scripts', 'wpso_theme_js' );