0

I have a JS file with a lot of functions that work with DOM manipulation. I added this hover event listener that was from W3 school and getting a 'Cannot read property 'addEventListener' of null' error.

  let hover = document.querySelectorAll(".center-nav a");


  hover.addEventListener("mouseenter", function( event ) {   
    // highlight the mouseenter target
    event.target.style.color = "purple";

    // reset the color after a short delay
    setTimeout(function() {
      event.target.style.color = "";
    }, 500);
  }, false);

Did some digging and read it's due to this event is loaded before the pages HTML. Which makes sense because the main.js file is leading in the head.

My functions.php

function mikes_files(){
    wp_enqueue_style('main-style', get_stylesheet_uri(), NULL, microtime() );
    wp_enqueue_script( 'prefix-font-awesome', 'https://kit.fontawesome.com/xxxxx.js' );  
    wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', NULL, microtime() );
}



add_action('wp_enqueue_scripts', 'mikes_files', 999);

Read that the 999 helps with make it load last, but its still in the head.

Do I make a different js file with the code and find the function needed that puts it in the footer?

Patrick Q
  • 6,373
  • 2
  • 25
  • 34
MPortman
  • 181
  • 1
  • 13
  • 1
    You might want to checkout [this](https://wordpress.stackexchange.com/questions/37960/cant-enqueue-scripts-in-the-footer) and [this](https://wordpress.stackexchange.com/questions/284072/how-to-add-js-in-footer) – Patrick Q Dec 12 '19 at 19:58
  • I'm voting to close because the `wp_enqueue_script()` documentation is pretty clear about loading in the footer: https://developer.wordpress.org/reference/functions/wp_enqueue_script/ – disinfor Dec 12 '19 at 20:38

2 Answers2

2

Change this line:

wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', NULL, microtime() );

with this:

wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', array(), microtime(), true );

In wp_enqueue_script there is an option to define whether to load the script in <head> or before </body>. By default wp_enqueue_script loads the script in <head> just pass the 5th argument to true to load it before </body>. For more details, please refer wp_enqueue_script documentation.

Also, querySelectorAll returns the NodeList and you can not call addEventListener using the NodeList. You should iterate over the NodeList, and apply addEventListener to each element.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
1

If you are using / can use jQuery, you would just wrap your function in $(document).ready(function(){ **your code**});. If you're using vanilla JS, check out Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Will
  • 26
  • 2