Using JavaScript and JQuery in Page

jQuery is default active in WP, no need to enable it.

There are 2 ways of including your own jQuery in WP:

  1. Enqueue your own file containing the jQuery (preferred method)
  2. Use the wp_head or wp_footer action hook to include a script with jQuery.

I’m only going to explain how to enqueue scripts in WP.

But first things first, if you want to include your own files it’s best to have a child theme active. Why? Because changes in a child-theme are not overwritten with an update. More information about child-themes here: https://codex.wordpress.org/Child_Themes

Almost every professional theme has the child theme included, simply upload it to the themes directory and activate it in WP.

Below are the contents of a simple jQuery file with your alert.

jQuery(document).ready(function ($) {
    alert("I am an alert box!");
}

As you can see, the $ is included in the function, no need to replace it with jQuery. Save & upload the file to your child-theme directory.

Next: You need to tell WP to include this file.
Open the functions.php in your child theme. Add the following function:

add_action( 'wp_enqueue_scripts', 'michael_enqueue_my_script');
function michael_enqueue_my_script() {
    wp_register_script( 'my_test_script', get_stylesheet_directory_uri() . '/your-file-name.js', array('jquery'), '0.0.1', true );
    wp_enqueue_script( 'my_test_script' );
}

I included the michael in the function name because you have to be carefull you do not create duplicate global function names.

When you enqueue files like this, it’s easy to add conditional logic. The example below only loads your file on the homepage:

add_action( 'wp_enqueue_scripts', 'michael_enqueue_my_script');
function michael_enqueue_my_script() {
    wp_register_script( 'my_test_script', get_stylesheet_directory_uri() . '/your-file-name.js', array('jquery'), '0.0.1', true );
    if( is_home() ) {
        wp_enqueue_script( 'my_test_script' );
    }
}

Regards,

Bjorn

Leave a Comment