How to Write a jQuery Plugin – Part 2: Options and Collections

In part one of my series on creating a jQuery plugin, I showed an example on how to structure a new custom plugin.  In this post, I’ll show you how to provide options for developers using your plugin and how to allow your plugin to handle multiple elements in the DOM.

User Options

You will remember in part one that we added an options parameter to our plugin’s main function.  It looked like this:

$.fn.highlight = function (options) {

This parameter is an object that will contain values for all of the options that the user will specify.  There is nothing special about this object.  It can hold any kind of data that you need to use as a setting for your plugin.  The problem with using this object directly is that we don’t want to require the user to set any options at all, if we don’t need them to.  However, we also don’t want to have to check to see if each value exists to specify a default.

jQuery’s built in extend function simplifies this down to a small piece of code.  See the example below:

var settings = $.extend({
     cssClass: 'highlight-yellow'
}, options);

In this snippet we are creating a variable in our plugin to hold our user settings.  To do this, we pass two things into jQuery’s extend function.  The first is an object that contains all of the default values that we wish for our plugin to use if the user does not specify their own value.  The second parameter is, you guessed it, the options variable containing the user’s specified values.  jQuery extend takes those two objects and merges them together, replacing our default values with the values in the options variable, if they exist.

In this case, I’ve added a very simple setting that will control the class that gets added to the content to highlight it in a specific color.  I will demonstrate how to use that in the next section.

Handling Loops and Collections

You may not realize it, but any time you are using a jQuery selector you are being returned a collection of elements.  This is the case whether or not there is or an only be one matching element on the page or not.  Selecting an element by class?  You get a collection of the elements that match that class.  Selecting an element by ID?  You still get a collection, but it contains only a single element.

This is important to understand because you will need to code your plugin to handle a collection of elements, rather than just one.  You can do this easily using jQuery’s each function.

return this.each(function () {
     // Adds the highlighter class to the element
     // Note the use of our settings object.

Inside of the each function is where we write the code for the core functionality of our plugin.  In this case, we want to add a class to every element that has been selected by the user. This will be how we add the highlight to each block of content.

Notice the use of the settings variable.  That object will contain either the default value or the user specified option value.  No extra work is required.

At this point, if we combine all of our code into a single file, we have a very simplified, but working plugin.  In the final part of the series, I will show you how to create your plugin file and complete all of the necessary steps to use it in an HTML page.

Until then, thanks for reading!


How to Write a jQuery Plugin – Part 1: Structure

One of the most beloved features of jQuery is that it is easily extensible. It requires little overhead to get a basic plugin started and it allows you to build reusable components on top of the power of jQuery. jQuery is already in use on many sites around the web. Creating a plugin allows you or other developers to easily drop your code into a site and start using it quickly.

Over the following three weeks, I will show you how to structure a basic plugin, provide a base set of features and how to package up and use your plugin on a page. Let’s get started this week with the basics of plugin structure.

Basic Structure

(function ( $ ) {
	$.fn.highlight = function (options) {
          // Our plugin code goes here.
}( jQuery ));

The code snippet above outlines the basic structure of a jQuery plugin.  This may look out of the ordinary to you if depending on how you have worked with JavaScript in the past.  Let’s break it down.

Attaching to jQuery

Our plugin begins on line 1 with some strange syntax for declaring a function inside of parentheses.  At the end of the function’s brackets we have the “jQuery” variable in parentheses.  What’s up with that?

This takes advantage of a behavior in JavaScript called Immediately Invoked Function Expressions.  (I won’t go into detail about all that can be done with IIFE, but you can find more information here.)  The purpose of this code is to make sure that your plugin will work side-by-side with other libraries.  There are many libraries that use the $ character to provide an alias or shortcut (jQuery and ASP.NET AJAX are just two of many).

The last line of our plugin immediately passes the jQuery function into our IIFE, allowing us to use the $ alias within the scope of our plugin whether it is in use by another library outside of the plugin or not.

Plugin Declaration

On line 2 of the code above, we declare the $.fn.highlight function.  This is the main entry point of our jQuery plugin.  The function declaration also includes a parameter called “options”, which we will deal with in later parts of the series.

By attaching our function to $.fn, this makes it available anywhere in your application that jQuery is in scope.  You will likely recognize the syntax below that we can now use to call our plugin.

$(function () {

On page load, this will call the highlight function in our plugin for every paragraph tag on the page.  Feel free to try it out.  To run the code properly, you will need to include the plugin code in a file and include jQuery in your HTML file as well.

At this point, we have no code in our main function, so nothing will execute when our plugin is called.  However, in later installments we will add our plugin functionality and work with user defined options.

Thanks for reading!  Feel free to leave a comment or share this post.  Please come back next week for part two!

ASP.NET MVC Validation Messages using jQuery UI Tooltips

Traditionally in ASP.NET you add a single Validation Summary above your form that describes the errors that the user has made, or add validation messages next to each control in the form to grab the user’s attention to each particular field.  The example below from the default MVC 4 application illustrates this.

Default Validation Behavior

The default validation behavior in the ASP.NET MVC 4 internet application.

The problem comes when trying to format a form with a large number of fields in a way that is pleasing to the user and also does not use much space on the screen.  jQuery UI tooltips are an alternative option.  The user would see a general message that some errors have occurred on the form or a style change to indicate the fields that are problematic.  This could be a red border around the field, or even an asterisk.  When the user clicks that field to change the data, they are presented with the full error message in a tooltip.  It works well in limited space and it’s flashy!

What You Will Need

This particular walk through uses a strongly-typed Razor view in an ASP.NET MVC 4 project.  Specfically, the Login view from the default “Internet Application” project generated by Visual Studio.  MVC 3 will work fine as well.  If your project does not include jQuery UI, you will need that as well.  The default project does have jQuery UI already included, but not the tooltip libraries, so I just included the newest version from jQuery’s CDN.

Setting Up the Validator

Most commonly, forms in ASP.NET MVC use the Html.ValidationMessageFor method to generate a validation message based on the model field that is passed in.  This causes a problem with jQuery UI tooltips because the ValidationMessageFor method generates span elements and other HTML around the message for formatting purposes.  What we need to use here is the ValidateFor method, which will attach all of our validation data to the input field.  We can still set all of our information in the model as we usually do, but with out all of the extra HTML.  Here are my modifications to the User Name and Password fields to use the ValidateFor method.

     @Html.LabelFor(m => m.UserName)
     @Html.TextBoxFor(m => m.UserName)
     @{ Html.ValidateFor(m => m.UserName); }
     @Html.LabelFor(m => m.Password)
     @Html.PasswordFor(m => m.Password)
     @{ Html.ValidateFor(m => m.Password); }

One thing should jump out at you right away, and that  is the usage of the ValidateFor method on lines 4 and 9.  ValidateFor is a void method that has no return value, so we need to call it inside of a code block instead of directly like we call Html.TextBoxFor.  A semicolon is necessary as well to terminate the statement.

Adding on a jQuery UI Tooltip

Attaching the jQuery UI tooltip to the control is a piece of cake.  All you need to do is add this snippet of JavaScript to your log in page:

<script type="text/javascript">
    $(function () {
            items: ".input-validation-error",
            content: function () {
                return $(this).attr('data-val-required');

We attach the tooltip only to fields that have the “input-validation-error” class. This allows us to only show the error if there is something wrong with the data that the user has entered. If the data for a field is OK, the user will never see the tooltip.  Our custom content function grabs the “data-val-required” attribute from the input tag to display as the tooltip mesage, which contains the validation message that you set in your model.

Validation with jQuery UI Tooltip

Validation with jQuery UI Tooltip

Here’s our new and improved (and much more compact) log in form!  You can see that we have the red borders to tell us which fields need updating, but the tooltips will hide unless the user focuses on the field.  In this case, the password validation message will show when the user switches to that input, and the User Name validation will hide.

The possibilities for styling and positioning the tooltip with jQuery UI are endless.  For example, you could add a bright red alert box and you could position it anywhere in reference to the field; above, below, or to the side.

It’s really that easy.  Please feel free to leave a comment if you have any questions.

Using jQuery 2.0 and supporting IE 8?

jQuery 2 has been released and the most talked about addition is actually the removal of a feature.  Notably, support for Internet Explorer versions 6, 7 and 8.  The jQuery blog notes that Android 2.x browsers are the next on the chopping block.  You may think that the new features in jQuery 2.0 would have to be substantial to encourage developers to use it and leave IE 8 behind, but at this point the APIs of jQuery 1.9 and 2.0 are identical.  In other words, they provide the exact same set of features, they just support different browsers.  In addition, both the 1.x and 2.x versions of jQuery will continue to be supported side-by-side for the foreseeable future.  jQuery 1.10 is will be released in the coming months with bug fixes from the 2.0 cycle.

The only noted benefit of the change to jQuery 2.0 is a decrease in size of the JavaScript file from 93kb to 83kb.  Some developers may see this change as negligible and continue to use jQuery 1.9, where those who support systems with much higher traffic may see a benefit in the reduced file size.  Why choose when you can serve the larger file to the browsers that need it and save the bandwidth for those that do not?

How To

Through the use of conditional comments, a site can use jQuery 1.9 to support just the IE 8 and lower users, and use jQuery 2.0 for all others, taking full advantage of the bandwidth savings when possible.  Conditional comments are commonly used to create IE-only stylesheets for those pesky quirks that only seem to occur in Internet Explorer.  However, there is nothing preventing them from being used for JavaScript as well.  See the following code example:

<!--[if lt IE 9]><!-->
<script src=""></script>
<!--[if gte IE 9]><!-->
<script src=""></script>

The first line checks to see if the requesting browser is lower than IE 9.  If it is, then we load jQuery 1.9.  The second line checks if it is greater than or equal to IE 9.  If it is, then we load jQuery 2.0.  Since the 1.9 and 2.0 APIs are identical, the rest of the calls to jQuery on the page will work properly with no additional changes required.  Take note that there are some additional comment tags included to make these checks visible to non-IE browsers such as Chrome or Firefox.


Many developers considered jQuery’s support for a wide range of browsers to be a significant benefit for choosing it over other alternatives.  Often a project’s targeted audience or the client themselves will determine what browsers need to be supported, leaving the developer out of the decision entirely.  With the newest version shifting from that support, the door may be left open for a competitor product to gain usage in the developer community.  At this point, there is no cause for alarm since the jQuery 1.x line will continue to be supported in the future.  However, if jQuery 2.0 begins to add features that are not available in 1, developers may demand a version of jQuery 2 with support for older browsers, or just move on to something new.  Only time will tell.