Add jQuery Scripts to WordPress

How to Add jQuery Scripts to WordPress


Add jQuery Scripts to WordPress

This Article is about Add jQuery Scripts to WordPress.

jQuery Scripts to WordPress 2019

Before we start attaching scripts to WordPress, let’s look at jQuery’s compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.

What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use JQuery instead. Take a look at the code below to see what I mean:

/* Regular jQuery */
$(.hideable).on(click, function() {
$(this).hide();
})
/* Compatibility Mode */
jQuery(.hideable).on(click, function() {
jQuery(this).hide();
})

The good news is that with a few modifications you can go back to the lovely little dollar sign once again! Writing jQuery out so many times makes the code longer to write and more difficult to read.

Just to recap if you’re learning jQuery, the $ sign is just an alias to jQuery(), then an alias to a function. The basic syntax is: $(selector).action():

  • A dollar sign to define jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

If you’re loading your script in the footer, you can wrap your code in an anonymous function, which will map jQuery to $. Here’s how:

If you want to add your script in the header – which you should avoid if possible – you can wrap everything in a document-ready function, passing $ along the way.

jQuery(document).ready(function( $ ) {
$(.hideable).on(click, function() {
$(this).hide();
})
});

Linking Your jQuery Scripts

Now that you can write a valid jQuery code for WordPress, let’s link our work to our website. In WordPress, the process is called enqueueing. For a regular HTML website, we would use the <link> element to add scripts.

WordPress ends up doing the same thing, but we’ll use special WordPress functions to achieve it. This way, WordPress handles all our dependencies for us – thanks, WordPress!

If you’re working on a theme, you can use the function within your function file. Here’s how.

function my_theme_scripts() {
wp_enqueue_script( ‘my-great-script’, get_template_directory_uri() . ‘/js/my-great-script.js’, array( ‘jquery’ ), ‘1.0.0’, true );
}
add_action( ‘wp_enqueue_scripts’, ‘my_theme_scripts’ );

Leave a Reply

Your email address will not be published. Required fields are marked *