WordPress 3.0 jQuery — Save 50%
Enhance your WordPress website with the captivating effects of jQuery.
In this article by Tessa Blakeley Silver, author of Wordpress 3.0 jQuery, we will cover the following things:
- Tips and tricks to properly load our jQuery scripts and making sure that they are compatible with other scripts, libraries, and plugins
- Some tips and tricks for using Firefox and Firebug to speed and aid in your jQuery development
- The virtues of valid WordPress markup and how you can make it easy on the site's content editors
(For more resources on WordPress and jQuery, see here.)
The following are the tips and tricks required for working with jQuery and WordPress.
Keep a code arsenal
A "snippet collection" or, what I call my "code arsenal" will go a long way to help you out, not just with jQuery and WordPress code, but also with the general HTML markup and even CSS solutions you create, not to mention any other code language you work in.
I'm terrible at remembering syntax for code, markup, and CSS. I often know what I need, but can never quite recall exactly how it's supposed to be typed. I used to spend hours going through various stylesheets, markup, and codes from previous projects to copy into my current project as well as googling (and "re-googling") web pages that had samples of the syntax I needed.
If you often find yourself in a similar situation, using the Snippets or Clip features that are usually available in good HTML/Code editors will free you from this mundane (and very time consuming) task. You simply type or paste the WordPress template tags, functions, PHP code, key CSS rules, and jQuery functions (and any other code syntax, whatever you find you need to use the most), into the Snippets or Clips panel available in your editor, and the application saves it for you, for future use.
As you work on different projects, you'll come up with solutions that you'll probably want to use again in the future, say, a set of CSS rules for unordered lists that make a nice gallery view, or a very clever use of two jQuery functions together. Every time you create something you think may come in handy (and a lot of it will come in handy again), be sure to save it right then and there, for future reference.
Good editors such as Dreamweaver, HTML-Kit, and Coda usually have the ability to organize snippets and keep them logically grouped so they're easy to access. Some editors will even let you assign custom "key shortcuts" and/or drag-and-drop to your clips right into your working file. How easy is that?
Free your arsenal
Once you discover how handy this is, you might want to have your arsenal available to other programs you work with, especially if you switch between multiple editors and authoring environments. I suggest you invest in a multi- paste/clip board application that lets you save and organize your code snippets. When I was on a PC, I used a great little app called Yankee Clipper 3 (which is free and is available at http://www.intelexual.com/products/YC3/), and now on the Mac, I use iPaste (which has a modest price; go to http://www.iggsoftware.com/ipaste/). In addition to having your arsenal handy from any application, being able to go back through the last 10 or so items you copied to the clip board is a real time saver when you're working on a project.
Your arsenal on-the-go
Last, I find I like to take most of my arsenal with me. If you use a handheld device or have a phone with a note app that lets you categorize and search for notes (especially the one that will let you sync from your desktop or a web service), you'll probably find it useful to keep some or all of your arsenal in it so you can easily look up syntax from your arsenal at any time. I occasionally freelance at places that require me to use one of their computers and not my laptop, so having access to my arsenal on my device is very useful.
Palm's native note app suited me great in this capacity for years and years; I now keep a large part of my arsenal in Google docs and use a little desktop app called NoteSync, which lets you write and view Google docs notes quickly (they'll have an Android app out soon, but in the meantime I use Gdocs on my Android device to see my notes). I have many friends who swear by EverNote's system (though, their mobile app only works offline on the iPhone and not on Android—as of yet).
Once all your often used and creative one-off solutions are all located in a convenient (hopefully categorized and key-word-searchable) place, you'll be amazed at the amount of speed your development picks up and how much more relaxing it is.
jQuery tips and tricks for working in WordPress
Let's start-off with some of my favorite jQuery tips and tricks, before focusing on WordPress.There are also a few nuggets that will help you speed up your jQuery development.
Try to use the latest version of jQuery
This is one of the drawbacks to using the bundled WordPress version: it may get a little behind the current version of jQuery until the next version of WordPress comes out. I'm all for staying on top of the current version as jQuery's top goals for version releases are not just to provide new functionality, but continually streamline and improve the performance and speed of the existing functionality. If the latest version of jQuery available on CDN is greater than the version that's bundled, be sure to deregister jQuery first or restrict your newer version with the if else statements, so it loads on the front end of the site on required pages only. Otherwise, you may create problems with plugins using the bundled version of WordPress.
Stay current with the Google CDN
Stay in No Conflict mode
The great thing about WordPress is that a site can have so many people contributing to it in lots of different ways: writing content, working on the theme, and adding WordPress plugins. One of the worst things about WordPress is that so many people can easily contribute who knows what to a site, depending on their admin status, some other collaborator could add to them, or what plugins they could install.
Staying in No Conflict mode is a must for WordPress. This in conjunction with using the wp_enque_script to load in WordPress will ensure that jQuery doesn't get "pushed out" if anyone loads up any other plugin that uses say MooTools or Scriptaculous, or even just an older version of jQuery.
It's easy to stay in noConflict mode. Just use jQuery instead of the shortcut dollar sign ($) in front of your scripts.
Make sure other scripts in the theme or plugin use the Script API
If you're using a theme or a plugin from a third party, take a look through the theme's header.php file or the plugin's PHP pages and double-check that all scripts have been loaded in using the register and wp_enqueu_script methods. I've had a few instances that were rather frustrating and caused some hair-pulling, as we tried to figure out why my jQuery scripts were not working or wondering how I "broke" them porting them over to the live site. Turns out, the live site had a plugin installed that my sandbox site didn't, and you guessed it, that plugin was including an older version of jQuery and a custom script file using hard-coded script tags instead of the wp_enqueue_script method. Once this was figured out and straightened up, setting everything into noConflict mode, everything worked fine again!
Check your jQuery syntax
This one always gets me. You write up a nifty little jQuery chain, add a few tweaks to it, and the darn thing just stops working. And you know it's right! Well, at least, you think it's right. Right? This is where a great code editor comes in handy. You'll want some nice find features that let you step through and look at each returned find, as well as let you run a find not just on the whole document, but on individual selections. I like to select the just the "offending chain" and run the following find features on it to see what comes up.
Colons and semicolons
Do a find for : (colons); you'll probably find a few that are accidentally set up as ; (semicolons) in your function's various object parameters, or you may have typed a colon where a semicolon should have been there.
I'll also run a find on closing parenthesis, ), and make sure each one that comes up is part of a continuing chain or the end of the chain marked with a;.
Mismatched double and single quotes
Last, a quick check for matched-up single and double quotes sometimes shows me where I've messed up. Panic's Coda lets you place in "wild cards" into the find so a search for "*' or '*" usually turns up a pesky problem.
Most good code editors have color-coded syntax, which really helps in recognizing when something isn't right with your syntax, such as not having a closing quote mark at all or parenthesis. But, the issues above are tricky as they'll still often display as proper color coded syntax, so you don't know until you run your script that something's wrong.
Use Firefox and Firebug to help with debugging
First up, there's the console.log and console.info statements which you can add to your jQuery scripts to pass info to and have a plethora of useful (and sometimes not-so-useful, but interesting) information about your script returned.
console.profile and console.time are great for measuring how fast you scripts are being processed by the browser.
For a complete overview of everything Firebug's console can do, check out: http://www.getfirebug.com/logging.
|Enhance your WordPress website with the captivating effects of jQuery.|
eBook Price: $26.99
Book Price: $44.99
(For more resources on WordPress and jQuery, see here.)
Know what jQuery is doing to the DOM
Another reason to love Firefox, as much as I love Opera and Chrome, when I can't select text and objects on the page and right-click on View Selected Source I'm at a loss and feel blind.
This is a great, quick, and an easy way to see if jQuery added that class, or wrapped those selected elements in your new div. Select what's generated by jQuery or should be affected by your jQuery script and right-click View Selected Source to see what's actually in the DOM.
Web Developer's Toolkit: View Generated Source
If you find having to make a selection confining and would like to see what the entire "generated" source is, you can use the Web Developer's Toolkit to see the page as affected by jQuery.
Seeing what Firebug sees
The most robust look at your generated HTML objects in the DOM, comes from using Firebug's HTML view. By selecting the HTML tab as well as the Click an element in the page to inspect tab, you can essentially run your mouse over any element and get an instant view of what it looks like in nested drop-down objects in the HTML view.
At first, I found this view a bit cumbersome as I was usually just trying to confirm the presence of a new object or manipulated attribute, but I quickly became accustomed to exactly how powerful it can be in helping me debug my jQuery scripts as we'll see in the next tip, where we'll even write selectors.
Tips for writing great selectors
Having a handle on your selectors means you'll be able to do anything you want with jQuery. Literally! I have yet to come up with a problem that I've had to push back onto the WordPress content editor. But sometimes when it comes to starting my jQuery scripts, targeting the selectors I need can prove a tad challenging, especially when working with an unfamiliar, custom theme.
Again, Firebug to the rescue. You can use the HTML view to select what you want to affect with jQuery and easily see how to construct a selector for it.
For example, take a look at the following screenshot's highlighted areas:
If we want to select that paragraph <p> tag, it becomes apparent that we simply write our jQuery selector for:
We can also see that we can get much more specific and target the id #post-125 if we only want to affect <p> tags in that particular post. By clicking in that top bar area that's displaying the hierarchy of ID and class names, on a particular class or ID, it will expand the object with that class or ID so we can fully see what our options are. For instance, we could also target paragraphs in the category-inkscape-illustration.
Don't forget about your selection filters!
Remember: sometimes it's easier to tell jQuery what you don't want to select using the :not filter or what you specifically want to select, such as the :first or :has() filters.
There you have it. jQuery selectors made easy! The more experienced you are in making jQuery selections, the easier you'll find it to generate your own HTML and objects to aid in your jQuery enhancements. This is useful because our next tip is all about making it simple for the site's editors.
Keep the WordPress editor's workflow "flowing"
Also, it puts more work back on me, eating up time that I could have been using to code up some other features for the site (entering content into the site's CMS, is not my favorite part of web development). jQuery changes all that and makes it very easy to write enhancements that can easily work with just about any HTML already on the page!
Despite just about everything being online "in the cloud" these days, most people don't have a knack of HTML. In fact, as we move full-on through Web 2.0 into Web 3.0, and beyond, less and less people will know any HTML, or ever need to, because of the great web-based applications such as WordPress and all the various social networking platforms that take the user's raw information and organize it as well as style and present it to the world for them.
If your enhancement requires the user to flip over into the HTML view and manually add in special tags or attributes, that's not an effective jQuery enhancement! Don't do it!
The user should be able to add in content and format it with the built in, Visual, WYSIWYG editor. You, the great jQuery and WordPress developer, will develop a solution that works with the available HTML instead of imposing requirements on it, and your clients and editors will be wowed and love you forever for it.
But my jQ script or plugin needs to have specific elements!
Your jQuery plugin may require certain elements to be present in the DOM to transform content into a widget or interaction.
Here's the thing to remember: if HTML elements can be constructed to make the enhancement work at all, you can create those HTML elements, within the DOM, on the fly with jQuery. You don't have to force your client to create them in the editor!
jQuery is all about selectors and it's true, sometimes, to get started you need something clear and unique to select in the first place! Work with the site's editors when coming up with enhancements. It's much easier for most content editors to wrap their head around having to simply apply a unique category or tag to certain posts in order for the enhancement to take effect, or even manually adding in keywords to a post's header or formatting content in a specific way. Look at all of these options first, with a site's editor, to make sure the enhancement is really an enhancement, for everyone.
WordPress tips and tricks for optimal jQuery enhancements
Just because you're up to speed with jQuery doesn't mean that you can neglect what's happening on the server-side with your WordPress installation. Let's take a look at a few key things to remember when dealing with WordPress.
Always use wp_enqueue_script to load up jQuery and wp_register_script for plugins for custom scripts.
You'll want to make sure you use wp_enqueue_script for all your jQuery loading-up needs. wp_enqueue_script and wp_register_script is WordPress' solution to keeping multiple versions of scripts from needlessly loading or canceling other versions out.
Always start with a basic, working, "plain HTML" WordPress site
Validate, validate, validate!
It's hard for jQuery to make those selections if your HTML is not well formed or broken. Often the fix comes from repairing HTML markup that's broken.
The easiest way to validate is to go to http://validator.w3.org/ and if your file is on a server, you can just enter in the URL address to it. If you're working locally, from your browser, you'll need to choose Save Page As and save an HTML file of your project's WordPress output and upload that full HTML file output to the validator using the upload field provided.
Also, Firebug's main console view automatically validates markup loaded onto a page. What's great about Firebug, you can select the error and be taken right to the offending line of code. I also find Firebug's explanation of what's wrong with it a little more understandable than some of the W3C's site, but then, Firebug also finds all sorts of "little things" that W3C doesn't and as far as I can tell, doesn't affect my jQuery development, so it's often a little simpler to use the W3C validator.
Check your PHP syntax
Just as with jQuery syntax, small, simple PHP syntax errors and typos always get me, even after all these years of experience.
If you're getting a PHP error, most of the time PHP will simply not render the entire page and display an error message with a note to the script page and number line in the code that's offensive. That makes it really easy to find and fix PHP issues.
Still it is possible to have a PHP syntax problem that doesn't throw an error. If you've checked everything else, take a quick run through the following common problems that happen with PHP.
Double check that you're not using any PHP shorthand. Make sure you have opening and closing <?php ?> brackets and make sure that you have php after the first bracket. Some systems don't have shorthand turned on and what works on your sandbox's hosted server or local server may not work on the live server. Avoid this by avoiding PHP shorthand syntax.
Check for proper semicolons
As with jQuery, because the syntax is rather simliar, you'll do well to use the find feature on your code editor and double check that statement closing semicolons are not written as colons : or commas , or missing altogether.
There you have it. I hope this list of tips and tricks for both jQuery and WordPress helps you out. We took a look at:
- Best ways to integrate jQuery with WordPress for maximum compatibility with other scripts, libraries, and plugins
- All the different ways that Firfox and Firebug are your development friend
- Tips and tricks for making sure you keep your WordPress user's job easy and your WordPress HTML valid and easy to work with
- WordPress and Flash 10x Cookbook [Book]
- WordPress for Business Bloggers [Book]
- WordPress Complete [Book]
- jQuery Plugin Development Beginner's Guide [Book]
- jQuery 1.3 with PHP [Book]
|Enhance your WordPress website with the captivating effects of jQuery.|
eBook Price: $26.99
Book Price: $44.99
About the Author :
Tessa Blakeley Silver's background is in print design and traditional illustration. She evolved over the years into web and multi-media development, where she focuses on usability and interface design. Prior to starting her consulting and development company hyper3media (pronounced hyper-cube media) http://hyper3media.com, Tessa was the VP of Interactive Technologies at eHigherEducation, an online learning and technology company developing compelling multimedia simulations, interactions, and games that met online educational requirements like 508, AICC, and SCORM. She has also worked as a consultant and freelancer for J. Walter Thompson and The Diamond Trading Company (formerly known as DeBeers) and was a Design Specialist and Senior Associate for PricewaterhouseCoopers' East Region Marketing department. Tessa authors several design and web technology blogs. Joomla! Template Design is her first book.