0

I am reading through the developer site for Wordpress and am just at the beginning of my learning of it. I have gotten my CSS to work via the wp_enqueue_style() but my javascript won't work via the wp_enqueue_script().

I have not added any Javascript on the pages themselves, I have the functions.php file with the wp_enqueue_script() in it which points to my /js/functions.js file where I want the toggleNav() function to work in for displaying the navigation menu differently on mobile.

What am I doing wrong? Here is my code:

functions.php

<?php 

   function my_theme_scripts(){
   wp_enqueue_style( 'style', get_stylesheet_uri() );

   wp_enqueue_script( 'functions', get_template_directory_uri() . 
   'js/functions.js', array(), '1.1', true );
  };

   add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

 ?>

functions.js

 function toggleNav() {
            var nav = document.getElementById("navbar");
            if (!nav.style.display || nav.style.display === "none") {
                nav.style.display = "block";
            } else {
                nav.style.display = "none";
            }

        };

I've even tried placing a function call in the footer.php but it doesn't work. When I add the javascript directly into the footer.php file it does work though.

Edit: Console output (I don't mind the images not being found as I'm just wondering about the js right now)enter image description here

  • did you check js file is enqueued properly or not ? can you see functions.js in view source ? – Chetan Vaghela Jun 20 at 11:29
  • In the source there is the following in the head (but I think it might be from the wp_head(), not sure): <script type="text/javascript"> window._wpemojiSettings =... </script> (I didn't add the whole script as it's too long for the comments) – Niall Jun 20 at 11:34
  • functions.js doesn't show up in Network though – Niall Jun 20 at 11:36
  • did you use child-theme ? – Chetan Vaghela Jun 20 at 11:37
  • 2
    please check in your header.php have wp_head(); AND in footer.php have wp_footer(); ? – Chetan Vaghela Jun 20 at 12:20
1

You must have to include wp_head() in header.php and wp_footer(); in your footer.php

header.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<?php
  wp_head();
?>
<body>

footer.php

 <?php wp_footer();?>
    </body>
    </html>

if you do not add wp_head() AND wp_footer() Wordpress hook does not fire using wp_enqueue_scripts hook .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.