Skip to content
Home » Blog » Adding JavaScript Libraries to WordPress

Adding JavaScript Libraries to WordPress

WordPress includes a number of JavaScript libraries because it uses those libraries in the administration screens. They’re available for you to use in your themes and plugins as well. The libraries include jQueryPrototypeScriptaculous, and SWFUpload. See the wp_enqueue_script Codex page for a complete list of the scripts available, along with their handles.

This code, added to your plugin or theme functions file, will add jQuery and its UI library:


<!--?php
//Including jQuery
function scl_add_jquery() {
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
}
add_action('wp_head', 'scl_add_jquery');
?>

Using jQuery in WordPress is a bit tricky. Most jQuery scripts rely on a dollar sign function. For example, $("div.main").addClass("wide"); would add the wide class to a div that already had the main class. However, several other libraries, including Prototype, use this same convention. Because WordPress also uses Prototype, the jQuery library is loaded in “no conflict” mode.

You have two options. You can use ‘jQuery’ in place of the dollar sign function (‘$’) throughout your script, or you can wrap your script in an extra function.

 
// using jQuery without a wrapper: replace $() with jQuery()
jQuery("div.main").addClass("wide");

jQuery(document).ready(function($) {
// $() will work inside this function; otherwise use jQuery()
$("div.main").addClass("wide");
});

What libraries are you using? Let me know some intresting JavaScripts libraries you have come across.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.