Include jQuery or JavaScripts in WordPress

Plugin and theme authors use jQuery for their special effects, but there seems to be some confusion about the proper way to include JavaScript files in WordPress. If you’d like to use jQuery effects on your pages or in your theme, or if you want to include any javascript plugin or personal script, read on to see how to do it properly with WordPress sites.

Queue Up Your Scripts with Actions

Since jQuery itself is already included in the core of WordPress, how should we include a javascript file that we’ve created or even one of the popular jQuery plugins that rely on jQuery? WordPress helps us in this endeavor with a function called ‘wp_enqueue_script()‘ and two actions that are used to call this special function.

The actions are used for either the user side or the admin side, depending on the purpose of your javascript. Use the ‘wp_enqueue_scripts‘ action to call wp_enqueue_script() for use in your themes. If the script functionality is needed on the admin side, use ‘admin_enqueue_scripts‘ action instead.

The format of the wp_enqueue_script() function call is as follows:

wp_enqueue_script('$handle', '$src', '$deps', '$ver', '$in_footer');

where $handle is the name of the script as a lowercase string, $src is the URL to the script, $deps is an array of scripts that the script you’re calling depends on or the scripts that must be loaded first for your script to work, $ver is the script’s version number in string format, and $in_footer is a boolean value to indicate whether the script should be loaded in the <head> or at the end of the <body> in the footer.

The $handle string is the only required parameter, so the other four parameters are optional. The $src, $ver, and $in_footer parameters default values are ‘false’, and $deps defaults to an empty array.

It seems that $src would need to be a required option, but WordPress already knows about several scripts and where to find them. Consult the list of default scripts included with WordPress to pick up their handles.

For example, to queue the jQuery Color plugin, we’d simply use this:

wp_enqueue_script('jquery-color');

To include a script and specify the source, try this for including the jQuery Cycle plugin in the <head>:

wp_enqueue_script('jquery-cycle', 'URL', array('jquery'), '1.3.2');

The URL should not be a hard-coded value for local scripts. Refer to the Function Reference pages in the codex for proper URL formats for plugins and themes.

Register Your Scripts First

Make sure that your scripts are registered first before calling them. Registering a script basically tells WordPress where to find the code for your script. Use the function wp_register_script() to specify the location and handle of your script. The format is similar to the wp_enqueue_script() function:

wp_register_script('$handle', '$src', '$deps', '$ver', '$in_footer');

The parameters have the same meanings and default values as used with wp_enqueue_script(). When in doubt, see what the WordPress Codex has to say about wp_enqueue_script() and wp_register_script().

Create a Function for the Header

Put it all together using wp_register_script(), wp_enqueue_script(), and the appropriate action to call the functions. Create a simple function, like id_scripts() below, and use the add_action() hook to queue up the scripts.

As a side note jQuery itself doesn’t have to be queued via a statement like wp_enqueue_script('jquery');, because it is listed as a dependency of ‘script-alpha‘ in this case.

When enqueuing a custom script that depends on a jQuery plugin, specify jQuery and its plugin in the $deps parameter of the wp_register_script() action for the custom script. For example, if your custom script depends on the jQuery Cycle plugin, which itself depends on jQuery, use array('jquery', 'jquery-cycle') for the $deps parameter. This specifies that both jQuery and its plugin Cycle should be loaded (in that order) before the custom script.

Place this code in the header.php of your theme. Remember, first register the javascript file, then enqueue it and make sure this is done before the wp_head(); statement. Your custom script can then be placed in header.php after the wp_head() call.

Use Theme functions.php to Safely Reference Your Script

When using a child theme take note that the header.php in a child theme will override the default header.php in the parent theme. Instead of placing the script-queuing code in the header, one could more safely put this code in functions.php. The advantage to that way is that the functions.php of a child theme is processed before the functions.php of the parent theme. Both the parent and child theme functions.php are processed, unlike header.php files.

If you’re the least bit unsure about messing with header.php, then just use functions.php to queue up your javascript files. Don’t forget the opening and closing PHP tags in functions.php, else it won’t work. Put the javascript that would come after the wp_head() call in a separate .js file in the child theme and you’re good to go.

Verify that everything is working correctly by viewing the source of the HTML document for a WordPress post that should have the script included. The <script> tags should be visible in the header or in the footer depending on how the scripts were called.

Slideshow Loading Problems Solved in jQuery Cycle

When it comes to JavaScript components that act on elements of the page, it is highly important to have those elements in place before the script tries to manipulate them, else things won’t work as intended. So, that begs the question, “What’s the best way to have JavaScript run on my page?” In this example we’ll focus on handling javascript while making slideshows with the jQuery Cycle plugin.

At any rate we want our pages to be seen by the visitor right away. We know if it takes more than a couple of seconds for anything to appear on the screen, the visitor is likely to click away to another site. Remember, text appears quickly when it’s not part of a table. The whole table has to be ready before you’ll see the table, so don’t use tables for design purposes, especially nested tables. Save your tables for presenting data.

A problem with big pages having slideshows is that if the page is not ready when a script tries to manipulate things, the effects may be all wrong. For example, when a script calculates the center position for an image it may get the positioning wrong, especially if all the images in the slideshow are not of the same size.

So, how do we improve our slideshow for the masses? We need to tell the javascript when to do its magic. In this example we’ll use this approach:

  1. Perform initial actions with the .ready() method. Actions in this case are to hide images with the .hide() method until they are called for by the script.
  2. Run the slideshow after the content has loaded with the .load() method.
  3. Use a function to calculate the center for each image.
  4. Apply the function with the before option in jQuery Cycle.

A previous post on centering slideshows with jQuery Cycle put all the javascript inside a .ready() statement. For many scripts this would be just fine, but for the slideshow it resulted in the action starting up before all the images were available.

For this example the slideshow is marked up as a group of images inside a <div> that has been assigned an id for JS targeting, #big_show, and a class for CSS targeting, .photos.

HTML Markup:

one two three four

Hide Images While Page Loads

Because it may take a while to load up all the photos for the slideshow, and everything else on the page, hide the photos except for the first one to start. Use a .ready() statement to hide the photos because we want to do that right away. Put everything in the .ready() method that you want to run first, even before the rest of the page or content has loaded. The .ready() function is a jQuery construct that allows you to bring functionality to the page before all the content has loaded. That way a page with lot of images can be useful even before all the images are visible.

For hiding images use the .ready() function so that this task will occur as soon as possible.

Many selectors could be used to target the first element in a series and the example above shows three ways of doing so for three different slideshows, #s1, #s2 and #s3. The outcome of each is the same in that only the first image is shown until the rest of the slideshow is loaded.

Control Slideshow Action After Window Loads

It makes sense to run a slideshow only when all the components for the show are present. To do that run Cycle with a .load() statement so that the slideshow waits to start until all of the images are loaded.

If you have a big slide show with lots of images, you might want to present an animated loading image until the slideshow starts.

Calculate Image Size for Centering in Slideshow

Take a look at the solution provided by “malsup” for users of his Cycle plugin:

Basically, what his code is doing is creating a function that will run before any slides are manipulated by Cycle. The purpose of the onBefore function is to calculate the correct margins for images and set the CSS parameters margin-top and margin-left for centering the images.

The onBefore function creates a variable called $slide to hold an array of the parameters of the $(next) element in the slideshow. The variables w and h are set to the width and height of said element via the $slide.outerWidth() and $slide.outerHeight() methods, respectively.

Finally, the margins are calculated from knowing the width and height of the slide container as set in the CSS (in this example 400 px and 300 px) and subtracting the slide’s width (w) and height (h) values, respectively. The margins only need to have half of the total margin value to accommodate both sides of the box, so the difference is divided by 2.

Use Cycle’s Before Option to Apply Centering Function

Using the onBefore function with Cycle’s before option works beautifully with images of different sizes, see line 5 of the .load() method above. Margins are set using the .css() method after they are calculated by the onBefore function.

CSS:

#big_show { 
    height: 400px; 
    width: 300px; 
    text-align: center;  
    background-color: #f3c; 
}
.photos img { 
    margin: 0;
    padding: 4px; 
    border: 1px solid #ccc; 
    background-color: #eee; 
    max-width: 290px; 
    max-height: 390px; 
}

You have to specify some CSS to get this thing to work right, namely set the width and height on the slide container and slides themselves.

Setting the max-width and max-height for the images helps to keep them inside of the container. Note that adding up the padding and border for both sides of the box is 10 px of the slideshow box that can’t be used to show an image. Therefore, the maximum image dimensions are the overall width or height minus 10 px. By accounting for the padding and border sizes a large image won’t overflow its container.

Any comments on this improved slideshow using Cycle plugin with jQuery?

Polaroid Slideshows with jQuery Cycle Plugin

The Cycle plugin for jQuery has many options that can be modified to create stunning slideshows. The look and feel of the slideshows are controlled with CSS and the behavior or animation of the slides is controlled by JavaScript. The Cycle plugin requires jQuery v1.3.2 or later.

Polaroid Photos

Sometimes you want to have a little fun with a project, like when somebody brings a Polaroid camera to a party. Taking Polaroid snapshots became wildly popular in the 1970s because it was the only camera that would produce a hand-held photo on the fly. All the other cameras had film that you would need to finish taking pictures on, and then send in to a photo developer to expose the negatives and print the photos. Polaroid cameras were like the iPhones of the 70s, and due to that popularity everybody knew what a Polaroid was — an instant photo.

Polaroid photos looked a little different from photo developer developed photos. They were always glossy and of a different format than the typical 3 1/2 inch tall x 4 7/8 inch wide snapshot that you’d get from the photo shop. With or without a border, the images on photo shop developed prints were rectangular, not square.

Polaroid cameras are still around today and their photos measure 3.5 inches wide by 4.25 inches tall. A white border around the image measures approximately 0.25 inch at the top, 0.1875 inch on the sides, and 0.875 inch at the bottom. The bottom border is larger so that you can write a caption there. Subtracting the size of the borders from the overall dimensions leaves 3.125 inches for the inner width and 3.125 inches for the inner height of the photographic image. Thus, Polaroid images are square instead of the standard rectangular format common in other photos.

Styling the Polaroid Photo

We can use CSS to make our images look like Polaroids. Introduce a dark, thin border and some padding for each image. In this case we’ll target the slides with the class .polaroid. Note that the container size may have to be enlarged to accommodate the padding and border from both sides of the image. This is especially important when all the images are not of the same dimensions.

CSS:

#slide_polaroid {
margin:10px;
z-index:3;
}
#write_caption {
position:relative;
top:-40px;
left:100px;
z-index:4;
}
.polaroid img {
padding:18px 14px 33px 14px;
}
.polaroid {
width:200px;
height:200px;
background-color:#fcfcfc;
color:#000;
padding:18px 14px 63px 14px;
border:1px solid #000;
position:relative;
}

The jQuery Cycle plugin is used to control the slideshow action. A function is called after each slide is shown on the screen to print the image alt text for the slideshow image captions.

JavaScript:

Output:

one
two
three
four

We’re getting close with the above, but a little better slideshow effect would be to bring the whole polaroid through the effect, not just the inner square image.

This brings up one of the nice features of using jQuery Cycle for slideshows: any content can be used for the slides. That means a <div> containing an image and textual content — such as a caption — could be identified as slides.

Polaroid Slideshow

For this example each image and caption is wrapped in a <div>, and Cycle is called like so:

HTML:

one

Slide 1 caption.

two

Slide 2 caption.

three

Slide 3 caption.

four

Slide 4 caption.

JavaScript:

Output:

one

Slide 1 caption.

two

Slide 2 caption.

three

Slide 3 caption.

four

Slide 4 caption.

This slideshow hard codes captions in the HTML instead of displaying the image alt text dynamically. It just depends on the purpose of the slideshow and how many slides you have as to which approach you’ll use for captions.

Styling Double Mat Framed Prints

Give your slides the look of double matted, framed photos with a little CSS and a different special fx.

one
two
three
four

Here, the .frame class is set to “ridge” for the <div> and <img> border properties using slightly different colors to make a double matted picture frame look. Black and grey backgrounds and a small amount of padding serves as the mat boards for the illusion. The JavaScript Cycle fx parameter is set to “fade” for the slideshow.

How To Turn On JavaScript

Need instructions to enable JavaScript for popular browsers? Here’s how to activate javascript in Internet Explorer, Firefox, Safari, Opera, Chrome and iPhone browsers with simple step-by-step instructions for PC and MAC users.

Just before the closing body tag, don’t forget to put a set of <noscript> tag with some content telling the user what’s up. What follows is a suggestion that directs the user on how to improve their system. Another approach would be to offer alternative content that doesn’t require any scripts.

<noscript>

Hello! To see all the cool effects on this page, you need to activate JavaScript in your browser. JavaScript is required for interacting with many of today’s top Internet sites, so you may need to know how to turn javascript on. The directions are slightly different depending on which browser software you use.

Visit activatejavascript.org for directions on how to activate javascript. If javascript is not enabled in your browser, a message will appear at the top of the screen: Your JavaScript is disabled!. Follow the directions to activate javascript for the browser and operating system that you’re using. Javascript will be enabled the next time you start the browser.

If the software that you’re using to view sites on the Internet doesn’t have javascript capability, try another more modern browser, like Firefox. PC, MAC and mobile versions of Firefox are available for free download at http://www.mozilla.org/.

</noscript>