Day 20: Using JavaScript Libraries in WordPress the Right Way

If you have worked with WordPress either as a stite owner or a developer you have likely run into situations where you add a plugin or a new theme only to find that some functions that previously work no longer work. This is in almost every case caused by JavaScript conflicts where the same library (or more often different versions of the same library) is called numerous times to do different jobs. The end result is a JavaScript conflict where nothing works.

What most poeple, WordPress developers included, don’t know is that WordPress comes pre-packaged with a whole whack of JavaScript libraries ready to be called and utilized. On this 20th Day of WordPress I’ll show you an example of how to utilize one of these libraries through the use of the wp_enqueue_script() function.

Hiding and revealing the comment section with jQuery

For a project I worked on earlier this year there was a feature request for the comments section to be hidden by default and then revealed only when the visitor clicked a link. The designer wanted the comments to be revealed using a smooth sliding reveal function. jQuery has just such a function, called .slideToggle().
We can write a simple function that will achieve our goal. It looks like this:

jQuery(document).ready(function($){
	$(".commentsKicker a").click(function(){
		$("#comments").slideToggle('slow');
		return false;
	});
});

The script looks for container with the class .commentsKicker that has a link in it and when that link is clicked, the contents of the div with the ID #comments will be revealed slowly using the .slideToggle() function.

To implement this script two things need to happen. First the jQuery librar has to be innitialized and then the function above needs to be set up. Common practice is to do this by placing a new jQuery library in the theme file, usually under a folder called “js”, calling it from the header.php or footer.php file and copying the function above straight into the same file. This is both clunky and completely unneccesary. A better option is to save the above script as a .js file in your theme and use wp_encue_script() to not only load the custom function but also associate it with the jQuery library WordPress carries with it.

Setting it all up with wp_encue_script()

Before we do anything else, let’s make sure we’re on the same page. In my single.php file I’ve placed a span with the class .commentsKicker and within it is the regular comments_popup_link() function. The comments section (to be hidden and then revealed) is wrapped in the regular #comments div (this is a WordPress theme default). Finally I’ve created a sub-folder in my theme directory called JS with a file called “reveal.js” that contains the JavaScript function displayed above exactly as it is displayed above.
With all that settled we can create a new function in functions.php that will at once call our custom JavaScript file, associate it with the stock jQuery library and enque both in our theme so they become active. Let’s do it step-by-step:
In functions.php of your theme create a new function:

function revealComments() {

}

Add an if statement to prevent the script from loading on admin pages:

function revealComments() {
	if (!is_admin()) {
	}
}

Register our custom script by giving it a name, defining its location and its library dependency:

function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );

	}
}

Enque the new cusom script so WordPress can use it:

function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );
		wp_enqueue_script('reveal');
	}
}

Finally, add an action that tells WordPress to initiate the new function upon first load:

function revealComments() {
	if (!is_admin()) {
		
		wp_register_script(
			'reveal',
			get_bloginfo('template_directory') . '/js/reveal.js',
			array('jquery') );
		wp_enqueue_script('reveal');
	}
}

add_action('init', 'revealComments');

With the new function and action in place the cutom JavaScript will automatically load and the fancy hide/reveal effect is added to the posts.

Further reading

The wp_enqueue_script() function is hugely effective and allows for a lot of advanced functionality. WordPress carries with it a whole slew of different JavaScript libraries and even if the library you want to use is not bundled into the application you can use wp_enqueue_script() to add other JavaScript libraries. The bottom line is if you want to use JavaScripts in your WordPress themes you should do it properly by way of wp_enqueue_script(). To get a full understanding of the function, its variables and many uses check out the WordPress Codex page.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.


About Morten Rand-Hendriksen

Morten Rand-Hendriksen is a staff author at lynda.com specializing in WordPress and web design and development and an instructor at Emily Carr University of Art and Design. He is a popular speaker and educator on all things design, web standards and open source. As the owner and Web Head at Pink & Yellow Media, a boutique style digital media company in Burnaby, BC, Canada, he has created WordPress-based web solutions for multi-national companies, political parties, banks, and small businesses and bloggers alike. He also contributes to the local WordPress community by organizing Meetups and WordCamps.

2 comments:

  1. Thanks for this (24 days of WordPress). I intend to peruse the entirety of the series for helpful hints.

    I’ve got a tip/addition: if, like me, you are using a child theme and end up placing the “js” folder you asked the reader to create, within the child theme, you’ll need to use the function instead of get_bloginfo('template_directory') will point to the parent theme not the child theme.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>