How to properly use jQuery scripts in WordPress?

I feel like I am definitely missing something simple here… but for the life of me, can’t find what I’m missing.

I am of the “bad habit” of including jQuery functions directly in the header.php file (among other spots). This is frowned upon, as I understand, and functions should be kept in a separate file using the wp_enqueue function to load them (if I get that correctly).

Read More

I’m attempting to following the solution given here:
How do I add a simple jQuery script to WordPress?

I have this simple function in my header.php that should fire on document ready:

<script>
    // Scroll to Top
    jQuery(document).ready(function () {
        // Force element to hidden state when page loads
        jQuery('.scroll-to-top').hide();

        // Check to see if the window is top if not then display button
        jQuery(window).scroll(function () {
            if (jQuery(this).scrollTop() > 200) {
                jQuery('.scroll-to-top').fadeIn();
            } else {
                jQuery('.scroll-to-top').fadeOut();
            }
        });
        //Click event to scroll to top
        jQuery('.scroll-to-top').click(function () {
            jQuery('html, body').animate({ scrollTop: 0 }, 800);
            return false;
        });
    });
</script>

So to do things “correctly”, I take my code out and placed it in myScripts.js (removing script tags of course). In my functions.php file, I’ve added this code:

<?php
    function add_my_script() {
        wp_enqueue_script(
            'myScripts', // name your script so that you can attach other scripts and de-register, etc.
            get_template_directory_uri() . '/js/myScripts.js', // this is the location of your script file
            array('jquery') // this array lists the scripts upon which your script depends
        );
    }

    add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>

But when I load my page, the script doesn’t work anymore.

EDIT

Thanks for the help so far… changing this line:

add_action( 'wp_enqueue_scripts', 'myScripts' );

to this:

add_action( 'wp_enqueue_scripts', 'add_my_script' );

resolved the error seen on the page.

Unfortunately, the code does not seem to fire off on the page any longer. I assume because it’s (document).ready it should be firing automatically (as it always did when I included it directly), but it doesn’t when I include the script in this manner. Ugh… thoughts?

Related posts

Leave a Reply

1 comment