Laconic: a New Way to Generate DOM Content from JavaScript

DOM Exception Tree

Content can be inserted into your page using innerHTML or outerHTML…


var container = document.getElementById("container");
container.innerHTML = "<p>Here's some new <strong>DOM</strong> content.</p>";

(Note that jQuery also uses innerHTML for DOM content manipulation).

It’s fast and easy — but it’s not without problems:

  1. Invalid HTML strings can be inserted which make errors difficult to spot and debug.
  2. You may encounter browser issues if you attempt complex activities such as using or modifying nodes in the resulting DOM content.
  3. Although it’s well supported, innerHTML is a proprietary technology and not part of the W3C DOM. It offends the standards gods.

So let’s look at the DOM-based alternative:


var newpara = document.createElement("p");
var newstrong = document.createElement("strong");
newstrong.appendChild(document.createTextNode("DOM"));
newpara.appendChild(document.createTextNode("Here's some new "));
newpara.appendChild(newstrong);
newpara.appendChild(document.createTextNode(" content."));
var container = document.getElementById("container");
container.appendChild(newpara);

Nasty. It’s three times longer, slower to execute and still prone to human error.

Several years ago I devised by own solution, BetterInnerHTML, which loaded an HTML string as XML, recursed the structure and inserted appropriate nodes into the DOM. It worked, but I was never totally happy with performance or issues such as HTML entities.

Fortunately, Joe Stelmach has devised an alternative. It’s a small standalone utility named Laconic which uses a logical JavaScript notation to map directly to HTML, e.g.


$.el.p(
	"Here's some new ",
	$.el.strong("DOM"),
	" content."
).appendTo(document.getElementById("container"));

Attributes are supported using object literal notation:


// produce <div class="example"><div>Content</div></div>
$.el.div(
	{ "class": "example"},
	$.el.div("Content")
);

I like it. While innerHTML remains the best option for quick and dirty DOM content generation, Laconic will be useful in those odd situations when it fails to work as expected.

For more information and downloads, refer to:

Validating WordPress Comment Forms with jQuery and a Custom Plugin

wordpresslogo.png

One of the newest ways that web designers are increasing the usability and accessibility of their websites is by employing a combination of PHP, XHTML, and jQuery programming to validate forms “on the fly” as users fill them out. With WordPress, several pieces of information are almost always required in order to post a comment. A user must provide their name, their email address, and the comment itself. Some websites even require that users supply their website information when they post a comment. That’s a lot to remember, a lot to fill out, and the room for error is pretty big. A standard WordPress installation does not validate forms until a user has already clicked the submit button, meaning they don’t see any errors until the posting process has been completed. This leads to plenty of frustration and it simply isn’t usable in the modern era of blogging and interacting.

To replace this old-fashioned way of validating forms and replying with a user error, developers have begun employing jQuery to validate forms as users fill them out. Users will see a message displayed under each form as they proceed through the commenting process, and that message will either inform them that they’ve filled out the information successfully or it will alert them to an error and advise them to make a correction. This all happens before the “submit” button is clicked, and it saves users a page load and a few minutes of frustration in the process. It’s easy to do, and the library for form validation is already written. The only thing that’s holding most users back is developing the custom plugin to make this possible in WordPress, and that’s not nearly as taxing as most might think it is.

Step 1: Create a Plugin Directory and Get the Files in Order

The process used to validate a form requires that a custom plugin be generated within WordPress. This might intimidate some users, but rest assured that this plugin is just a more extensive series of additional “functions” like those that would typically be placed within a site-specific “functions.php” file. The validation function is added to a plugin so that it can be used across themes, rather than theme-specific functions files, which would require placing this code within every single one in order to make sure it works thoughout each user-installed theme in the Dashboard.

First and foremost, navigate to /public_html/wp-content/plugins/ and create a new folder named “validation-plugin.” This will contain all of the relevant files and subfolders needed for proper operation. Open that folder and create two new subfolders for the plugin:

  • js
  • css

These folders are pretty self-explanatory. Inside the “js” folder, a jQuery library will be stored. Inside the “css” folder, a stylesheet will be placed, which will determine the appearance of the error or approval messages that are displayed to the commenting user.

The jQuery library needed for this process is known as the Bassistance.de Library. Once it has been downloaded, it should be placed into the “js” folder. Then create a new file called “validation.css” and place that (blank) stylesheet into the “css” folder. Finally, it’s time to create the plugin PHP file that will control the validation functions.

The PHP plugin file should be named “form-validation.php” and it should be placed outside the subfolders in the main plugin directory. This file can be left blank for now, as it will be edited directly on the server and filled with content and functions as the process continues.

Step 2: Give the Plugin a Name and Describe its Functions

Every WordPress plugin is required to contain a few lines of code which give it a name, a version, and some descriptive tags and blocks of text. This is much like the content placed in a “style.css” file, and it’s just as important. A plugin which lacks these lines of text won’t display in the WordPress Dashboard. That means it cannot be activated after completion, so be sure that each line of text is filled in completely with the proper information. These lines of text look like the following:

/**
* Plugin Name: Comment Form Validation Custom Plugin
* Plugin URI: http://your-site.com
* Description: This plugin enhances the WordPress comment form by using a jQuery library to validate the content of each text area and text box as the user types their information into them. This plugin can be used across themes and is compatible with all major browsers and even screen readers.
* Version: 1.0
* Author: Your Name (You're the Author!)
* Author URI: http://your-site-again.com
* License: GPL
*/

Each line in the above code is pretty self-explanatory. The only one which might throw some developers off is the “license” line. For novice users, this simply refers to the license under which the code is written and distributed. In this case, it has been defined as GPL, for GNU Public License. This pretty much means that anyone can use this code on their own website, or modify the code to their needs, so long as they give credit to the original author. Because WordPress is an open-source content management solution based on PHP, a GPL or GPL version 2.0 license is the most appropriate way to create, share, and minimally restrict your work.

Step 3: Bringing the jQuery Library to Life Using Plugin Functions

The next step of the process will add specific functions to the plugin’s PHP file, which will load the script and activate its functions on the comment submission website. This is done relatively simply and it looks exactly like something that would appear in a theme-specific “functions.php” file. Remember that this information and coding is based on using the appropriate plugin file directories, which were described in an earlier step of this process. The code, when completed, looks like this:

function form_validation_js() {
  if(is_single() ) {
    wp_enqueue_script(
      'jquery-validate',
      plugin_dir_url( __FILE__ ) . '/js/bassistance.js',
      array('jquery'),
      '1.8.1',
      true
    );
    form_validation_style(
      'jquery-validate',
      plugin_dir_url( __FILE__ ) . '/css/validation.css',
      array(),
     '1.0'
    );
  }
}
add_action('template_redirect', 'form_validation_script');
function print_validation_script() { ?>
< ?php } add_action('form_validation_script'); ? >

These can be customized to a user’s wishes and they can contain any punctuation or uppercase letters that a designer wants to include. Try to keep them brief and descriptive, however, as most people don’t read between the lines even when it’s well-styled using CSS code. The PHP programming part of this operation is now complete.

Step 4: Styling Error Messages with Some CSS

Now we’re going to use the stylesheet file that was created in the first step of this process. Navigate to the “css” folder and, in the “validation.css” file, add the following lines:

label.error {
  display: block;
  color: #000;
  background-color: yellow;
  padding: 10px;
}

Every error message is defined as a form label with the class “error.” This element simply styles these errors with black text, a yellow background, and design-friendly padding that keeps text from meeting the edge of the color. It can, of course, be customized according to your taste and your website’s design specifications.

Also worth noting is that this stylesheet information does not need to be placed into the plugin’s stylesheet at all. Because WordPress naturally draws its look and feel from the theme’s “style.css” file, it could be placed in that stylesheet instead. If your site uses multiple themes and switches them very often, or if you allow users to switch between your site’s installed WordPress themes, this is a great way to ensure that the comment form’s error messages blend in with each theme individually rather than inheriting a universal style from the plugin folder itself.

Be sure to test each form element and try to make it produce an error. Check out the styling, and the error message, and check for any bugs or glitches. If none exist, the process is complete and your website is now much more usable and accessible.

10 Tips for Developing Better jQuery Plugins

435-jquery-143

There are some great jQuery plugins. The better ones are adopted by thousands of web developers throughout the world. Unfortunately, the worse ones fail and disappear into obscurity. Here are some tips to ensure your plugins reach their full potential…

1. Don’t Break the Chain

Unless your plugin returns a value, the last line of your plugin function must be:


return this;

this ensures method calls can be chained, e.g.


$("div#myid").yourPlugin().anotherPlugin().yetAnotherPlugin();

2. Make it Easy to Use

In most cases, your plugin should simply work without the developer having to wade though documentation, set options or edit your plugin code.

If it’s a visual widget, the developer shouldn’t need to edit any JavaScript. You can simply provide HTML with a class/ID which will automatically launch your code, e.g.


<section class="myjqWidget">
<p>My content</p>
</section>

Your plugin can initialize itself, e.g.


$(function() {
		$("section.myjqWidget").myjqWidget();
});

3. Use Suitable Naming and Version Control Numbers

There are a lot of jQuery plugins. If you’re considering the name “tab” for your tab-handling plugin, there’s a strong possibility it’s been used already. That may not always matter but avoid using names which are ambiguous or likely to clash.

Version numbering is also useful. It’s becomes especially important when developers report problems.

4. Use a Closure

Never depend on ‘$’ referencing jQuery. If the developer has another library installed, it may have grabbed it before jQuery was loaded. The simplest way to solve the issue is to pass jQuery as the ‘$’ argument for an anonymous self-starting function, e.g.


(function($) {
	// code here can use $ to reference jQuery
})(jQuery);

5. Set Default Parameters

Most plugins set parameters using JavaScript object literal notation, e.g.


$("#select").MyPlugin({opt1: 1, opt2: 2, opt3: "three"});

This has several advantages: parameters are easy to read, can be ordered in any way and omitted completely. However, you should set defaults within your plugin code and override them accordingly, e.g.


$.fn.PlugIn = function(opts) {
	// default configuration
	var config = $.extend({}, {
		opt1: 1,
		opt2: 2,
		opt3: 3,
		opt4: 4,
		opt5: 5
	}, opts);

Your plugin can then reference parameters using code such as config.opt1.

6. Support HTML Parameters

Ideally, HTML widgets should be able to set parameters without the developer needing to change JavaScript code. You could consider HTML5 data attributes, e.g.


<section class="myjqWidget" data-opt1="1" data-opt2="two">
<p>My content</p>
</section>

These can be accessed via jQuery’s data method: .data("opt1").

7. Document Your Code

Add concise comments to the top of your plugin which describe:

  • the plugin name and version
  • what the plugin does
  • example uses
  • the parameters
  • contact and support links

If it’s particularly complex, consider a separate readme file.

8. Test Your Plugin Thoroughly

Test it. Then test it again. In all browsers.

There may be issues you’re not prepared to fix, e.g. IE6 compatibility problems. That’s fine, but ensure it’s mentioned within your documentation.

9. Use a Good Template

Here’s the template code I use when creating a new plugin:


/*!
 * jQuery plugin
 * What does it do
 */
(function($) {
	$.fn.PlugInName = function(opts) {
		// default configuration
		var config = $.extend({}, {
			opt1: null
		}, opts);
		// main function
		function DoSomething(e) {
		}
		// initialize every element
		this.each(function() {
			DoSomething($(this));
		});
		return this;
	};
	// start
	$(function() {
		$("#select").PlugInName();
	});
})(jQuery);

It provides a good starting point:

  • The plugin is wrapped in an enclosure.
  • It sets default options which are overridden by plugin parameters.
  • Each selected element is passed to the DoSomething function as a jQuery object.
  • return this; is included.
  • Auto-start code is provided at the end.

10. Get The Word Out

If you want developers to use your plugin, upload it to repositories such as GitHub, Google Code and jQuery Plugin directories. Create demonstration pages, publicize it in articles and tweet about it incessantly.

Then be prepared to support the plugin and update it when necessary. You will receive dumb questions and bizarre feature requests, but that’s all part of being a successful plugin author.

Do you have any top-tips for effective jQuery plugin development?

New Kicks and Tricks: jQuery Mobile (book excerpt)

jQuery: Novice to Ninja, 2nd Edition - New Kicks and Tricks

If you haven’t yet downloaded the free sample chapter of Earle Castledine and Craig Sharkie’s latest magnum opus for SitePoint, jQuery: Novice to Ninja, 2nd edition – New Kicks and Tricks, it’s high time you did. Or just cut straight to the chase and buy the book!

Why? Well, as someone who bought the first edition, I can vouch that there is plenty of new material in this edition, and the sample chapter is an excellent example.

Tell you what: let’s just take a look at it now. Here we go.

No exploration of advanced jQuery and jQuery plugins could be complete without a hat-tip to the newest kid on the block, jQuery Mobile.

Mobile moves jQuery away from the desktop and onto, well, “mobile” devices. Better yet, it builds on the lessons learned by both Core and UI, so even if you have only a passing understanding of those projects you’ll be ready to roll with Mobile. In fact one of the toughest things to come to terms with when you’re developing with Mobile is the extra steps it’ll take to view your handiwork in the target platforms.

No more ALT+TAB and refresh for Mobile developers—it’s now CTRL+S, pick up your phone or tablet PC, and hit reload.

jQuery Mobile blends the cross-browser and cross-platform support we know and love from jQuery with the power, flexibility, and design we turn to UI for—it’s a plugin, but not only does it extend  jQuery, it extends the places where you can rely on jQuery. You can select, bind, animate, and chain as you’d expect from a plugin, but you can also tap and swipe, use more CSS3 than ever before, and, most importantly, use your mastery of jQuery to make that next must-have application.

You’re able to focus on your application’s goal and let Mobile help you out without getting in the way—include two files, à la jQuery UI, and you’re away!

<link rel=stylesheet href="http://code.jquery.com/mobile/1.0/
➥jquery.mobile-1.0.min.css">
...
<script src="http://code.jquery.com/mobile/1.0/
➥jquery.mobile-1.0.min.js"></script>

Looks familiar! Like you’re accustomed to, you can use jQuery’s own CDN to deliver your files as we’ve done here, or you can grab the files yourself and include them locally.

Using jQuery’s CDN, your minified and zipped files come in at 7kB and 24kB respectively—easily small enough to be useful on a mobile network. And you’ve got a host of platform options to access those mobile networks with. As it says on the jQuery Mobile website, “Mobile has broad support for the vast majority of all modern desktop, smartphone, tablet, and e-reader platforms.”

And this is no small claim: jQuery Mobile’s graded browser support matrix sees it catering to an impressive two dozen target platforms. This is not bad if you consider that some of the competitor products officially support only one.

Four Grades of Support

There are too many platforms for us to duplicate the full list of the graded support matrix, but you can find them all on the jQuery Mobile site.

Instead, let’s take a look at the coverage levels you can expect for each grade:

  • A-grade: full, enhanced experience with Ajax-based animated page transitions
  • B-grade: enhanced experience without Ajax navigation features
  • C-grade: basic, non-enhanced HTML experience that is still functional
  • Not Officially Supported: might work, but hasn’t been thoroughly tested or debugged

Mobile’s documentation is nearly as comprehensive as the support is. Each method and property is covered, and the documentation itself is written using Mobile —clever, huh? Arguably the documentation is easier to navigate on a smartphone than it is on the desktop!

As plugins go, jQuery Mobile is even more rich than jQuery UI—it has more features baked in, and more functionality that works as soon as you add the files to your application. And as Mobile is grounded in the HTML5 and CSS3 that are driving desktop development, it can even be enticing to non-mobile use cases.

Its support is still growing, and there are possibly some features that we’ll see added in later releases.

While Mobile doesn’t yet rate a mention in the navigation of jQuery Core or UI sites, there are myriad features to make applications that belie just how new the library is. Let’s take a look at some of those features.

Playing Your Trump

By now we know our client nearly as well as we know jQuery and jQuery UI, so it’s a safe bet for us that a mobile application with a social aspect is on the cards.

Let’s up the ante and deal with their next request by creating a mobile-based card game.

We’ll implement jQuery Mobile by making Pop Trumps: The Jemimas, the world’s first card game that combines the thrill of trumping your friends with the face of the newest rock star to hit the charts, as seen in Figure 4.1, Figure 4.2, and Figure 4.3.

The face of Pop Trumps
Figure 4.1. The face of Pop Trumps
 
Pop Trumps home page 
Figure 4.2. Our Pop Trumps home page

winners's screen 
Figure 4.3. The winner’s screen

Rather than go through every line of code, let’s focus on the Mobile-specific code where we can:

<link rel=stylesheet href="http://code.jquery.com/mobile/1.0/
➥jquery.mobile-1.0.min.css">
⋮
<script src="http://code.jquery.com/mobile/1.0/
➥jquery.mobile-1.0.min.js"></script>

We have already looked at the Mobile requirement includes, but they are worth mentioning again. Unlike other jQuery projects, and in order to achieve the wide range of platform support, a great deal of manipulation occurs well before the document.ready event fires. As a result, we need to add our includes in the head of our document to achieve the best user experience.

While we’re in the document head, let’s look at that new meta element:

<meta name=viewport content="width=device-width, initial-scale=1,
➥user-scalable=0">

jQuery Mobile draws heavily on HTML5, and here we have an HTML5 element that normalizes the cross-platform display of our application. It tells our browser that our content should be as wide as it  can be and that it should be at a 1:1 scale. This is important, given the wide range of resolutions our application may encounter.

That last content value—user-scalable=0—tells our browser not to make our content zoom. If zooming is something you’d like in your app, just omit that value and go with the browser’s default behavior.

Speaking of HTML5, let’s take a look now at our document structure. Again, if you have already worked with HTML5, there should be few surprises for you—except possibly how well Mobile embraces the language.

<section data-role="page" id="home">
⋮
</section>
<section data-role="page" id="albums">
<header data-role="header">
⋮
</header>
<div data-role="content">
⋮
</div>
<footer data-role="footer">
⋮
</footer>
</section>
<section data-role="page" id="album">
⋮
</section>
<section data-role="page" id="results">
⋮
</section>

At its heart, our page is a group of section elements with a data-role attribute of page. You could also use div elements instead of sections—here, the attribute is more important than the element, as the data-role tells Mobile each of the sections will be a page in our application. We further delineate our pages with unique id attributes that serve as anchor targets for our navigation. Where a desktop might use ids to jump or scroll to content, Mobile uses them to transition between pageviews.

Inside our second section we’ve shown our basic pageview layout—a header, div, and footer, again all with data-role attributes that help Mobile apply its under-the-hood changes. Inside these  elements we just add whatever HTML we need and apply data-role attributes where it suits. Let’s try some now:

<a href="#albums" data-role="button">START</a>

Our first section with the id of home has an anchor which we tell Mobile we’d like to display as a button in our UI—we simply provide the data-role of button, and Mobile does the heavy lifting for us. Using the hash reference in our anchor is all we need do to load our next section, with an id of albums, into view.

In our albums section we continue using the simple HTML5 data attribute-driven approach. We tell our header to apply a theme using, you guessed it, data-theme.

We do the same for our unordered list, as well as telling it to be a data-listview, and the anchors in the list to have a data-transition of flip to control how our pages “turn”:

<header data-role="header" data-theme="b">
<h1>Pop Trumps</h1>
</header>
<div data-role="content">
<p>Select an album by The Jemimas to play</p>
<ul data-role="listview" data-inset="true" data-theme="b">
<li><a href="#album" data-transition="flip">
➥The Jemimas: Debut</a></li>
<li><a href="#album" data-transition="flip">
➥This is The Jemimas</a></li>
<li><a href="#album" data-transition="flip">
➥Awkward Third</a></li>
<li><a href="#album" data-transition="flip">
➥Best of The Jemimas</a></li>
</ul>
</div>

Tapping the anchors in our attractively styled listview will now cause the album-designated page to “flip” into to view, which adds nicely to our card-like effect. You can also use slide, slideup, slidedown, pop, and fade; if you’re a fan of jQTouch,you might notice that these transitions have been ported from that library with only minor changes. After our flip we’ll have dealt one of our cards, and the players can get into some serious trumping. For us, though, the real interest lies in three new data-roles and a seamless DOM manipulation:

<div data-role="content">
<div data-role="fieldcontain">
<label for="flip-a" class="ui-hidden-accessible">
➥Select slider:</label>
<select name="slider" id="flip-a" data-role="slider"
➥data-theme="c">
<option value="no">&#9756; Number 1s</option>
<option value="yes">6</option>
</select>
⋮
</div>
</div>
<footer data-role="footer" data-theme="c">
<div data-role="controlgroup" data-type="horizontal">
⋮
</div>
</footer>

The first new data-role is a fieldcontain, which does what you’d expect: contains fields. If you like, this data-role can be applied to a fieldset for some extra semantic sugar. The next is the slider role inside our fieldcontain, and the last is a controlgroup, which draws its name from an HTML5 hgroup and is used to group buttons.

The DOM manipulation triggered from a slider data-role shows Mobile’s roots in jQuery UI—the select element and its associated label are hidden in the interface and replaced by a sliding flip-toggle switch popular in mobile devices and illustrated in Figure 4.4.

Flip toggle
Figure 4.4. jQuery Mobile flip-toggle and grouped buttons

The controlgroup value has a no-less-striking effect in the interface, which it achieves using CSS alone (no DOM manipulation). By itself, the controlgroup value draws the links together and applies rounded corners to the first and last elements in the group. If you also add data-type=”horizontal” to the div containing the controlgroup value, as we’ve done in the preceding markup, the grouped buttons display in a row as you’d expect.

And our last data attribute is data-direction=”reverse”, which works with our transitions by reversing them. For example, where the default behavior is for a view to move in from the right of the screen, our data-direction attribute causes it to go out toward the right. When controlled, it provides the user with a strong sense of movement within the application. It doesn’t simply shift along an apparently endless series of views; rather, it moves around a series of pages like moving through chapters in a book:

<a href="#album" data-role="button" data-direction="reverse"
➥id="continue">CONTINUE</a>

And speaking of moving through chapters, we’ve reached the point where we can start talking about writing our jQuery Mobile code. Well, almost.

Before we talk about the code we’ll write, we need to cover one more piece of code that runs without us doing anything: the mobileinit event. jQuery Mobile’s default transformations and styling are so good you’ll have little need to apply any changes, but for those rare times when they are required, you can leverage the mobileinit event—it allows you to extend or configure options as soon as the event fires.

This means you won’t need to overcome defaults—you can change settings before they’re applied, and there’s no need to wait for the DOM to load. So you won’t have to wait for $(document).ready() to take effect, nor document.loaded.

As a result, it’s recommended you reference your own local script files after referencing the jQuery library, as normal, and before referencing Mobile, like so:

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="../path/to/your/scripts.js"></script>
<script src="http://code.jquery.com/mobile/1.0/
➥jquery.mobile-1.0.min.js"></script>

So we have sorted our semantic HTML, our source files are all in place, and the mobileinit event has fired. Let’s take a look at the code we’ve written to bring our game to life …

But that’s where we must leave our excerpt. As well as downloading this free sample chapter, you can also browse the Table of Contents and Index before you decide to buy jQuery: Novice to Ninja, 2nd edition – New Kicks and Tricks by Earle Castledine and Craig Sharkie.

Take the jQuery Ninja Test

jQuery: Novice to Ninja, 2nd Edition - New Kicks and Tricks

jQuery: Novice to Ninja, 2nd Edition - New Kicks and Tricks

Hey there, all you JavaScript and jQuery wannabes!

As part of the launch of our latest book “jQuery: Novice to Ninja, 2nd Edition. — New Kicks and Tricks” we’re laying down the challenge for all of you to test your jQuery knowledge. Below, you’ll see a screenshot of the first of nine sets of questions from our jQuery Ninja Test.

Take the QuizTake the test, and see if you can attain jQuery Ninja status!

Awesome Links #3

Checkout this awesome sliding boxes tutorial. A great tutorial with a moving box effect. A demo link is also included at the top of the page. Nothing to do with Web Dev at all but Slapometer is a Flash built site where you can give a British MP a good slap! Vital in the run up to the election. Super 3D Box Gift is a tutorial to create a box with items exploding out, all in 3D. Its a great tutorial and the end result is amazing.