Archive for the ‘jQuery’ Category

jQuery Plugin – hoverFade

June 4, 2010

I just wrote a new jQuery plugin that adds a fading-in effect when you hover over certain elements. I’m using it to add the fading rollover states on the top nav and on the social boxes in the footer.

Download

  • hoverFade The original plugin, unminified, with comments. 1.4 Kb
  • minified hoverFade A minified version (it also contains the license, to shrink filesize even more move this into a separate text file) 908 bytes

Usage

Using the plugin is simple, but there are several steps you should follow:

  1. First you should set up standard CSS hover states from the elements you want to add the effect to. This should be done using a class name on the container of the fading elements. This is so that basic CSS hovers are still used if JS is disabled on the client.
  2. Add selectors that show the same background image as the CSS hovers using a different class name. This different class name will be applied to the container and the CSS class name will be removed.
  3. Link to the plugin file from (ideally) the bottom of the page, after linking first to jQuery
  4. Call the plugin method on the same element that the CSS class was added to. if you use the default class names used by the plugin, and call the plugin on a standard list of links the plugin should just work.

The plugin contains 5 user-configurable options, all with sensible defaults:

newClass: "hover-anims", //class added by the plugin
classToRemove: "hover-css", //CSS-fallback class removed by the plugin
onClass: "on", //element with this class is not affected by hovering
trigger: "a", //element that triggers hover animations
faderTemplate: "<span />" //element which animates

Replace these with the classes you are using, or for minimal config use the same classes in your CSS. The trigger can be another element if you wish. The fader template should be an HTML tag and if inline, such as the default span element, it should feature a closing slash or it will not work correctly in IE. The fader template element is automatcially created and added by the plugin.

Take a look at the CSS I used for either the top nav menu or the social boxes to see how the CSS-fallback and JS classes can be used

Adobe-style checkboxes

May 28, 2010

I really like the how layers can be selected in Photoshop and Fireworks by holding the mouse button down and dragging the cursor over the check boxes. I always miss this feature on web forms with more than a few check boxes on them, so I thought it would be a great idea if it could be replicated.
Adding this functionality is extremely easy, all we need is the following script:

<script>
  (function($){

    //listen for mousedowns over target area
    $("fieldset").mousedown(function(e) {

      //stop text selection
      e.preventDefault();

      //stop text selection in IE
      if (window.ActiveXObject) {

        var fset = document.getElementById("checkers");
        fset.onselectstart = function () { return false; }
      }

      //add mouseovers to checkboxes
      $("input[type=checkbox]").mouseover(function() {		

        //toggle checked state
        ($(this).attr("checked") === false) ? $(this).attr("checked", "checked") : $(this).attr("checked", "");
      });
    });

    //stop listening to mouseovers when mouse button released
    $("fieldset").mouseup(function() {
      $("input[type=checkbox]").unbind("mouseover");	

      //stop unselecting text
      $("fieldset").unbind("select");
    });
  })(jQuery);
</script>

Easy right? Let’s look at what we do; first we set a mousedown event on the

because it’s the container of the check boxes and it gives the visitor plenty of target area to click and hold over. To stop any text in the parent container, such as the labels or the legend, from being selected we can use the preventDefault() method for most browsers.

IE will still allow text selection however, so we also need some additional code just for IE. The code is wrapped in a conditional that looks for the ActiveXObject, which I find a quick and easy solution in those rare times that browser detection instead of feature detection is required. To prevent the text being selected in IE we can return false from the onselectstart event which is fired by the browser as soon as any text is selected.

Next we attach a mouseover event to each of the check boxes; whenever this occurs we just test whether the check box is checked and if not we check it. If it’s already checked we uncheck it. Simple.

We also add a mouseup listener to the

so that the check boxes aren’t interacted with after the mouse button is released.

Try it out below.

Select or deselect options by clicking and dragging the mouse pointer over the checkboxes.






Review of jQuery 1.4 by Karl Swedberg and Jonathon Chaffer

March 16, 2010

I recently read through the newest revision of Karl and Jonathon’s amazing jQuery reference manual, which has just been updated for the latest release of the jQuery library itself. Even though it’s a reference manual used to refer to specific methods or properties of the library rather than a teaching book that takes the reader on a journey through the API I still wanted to read through it in its entirety in order to give it a balanced review and to see how much additional information it provided. I’m already fairly competent in using jQuery so I wanted to see if there was anything new it could show me. It did – there were subtle aspects to a number of methods that I had never used before, and with the new additions to the guide added for jQuery 1.4, there was actually a lot I took away from this book.

jQuery 1.4 Reference Guide

The first chapter served as a very good general introduction to jQuery and what the library is capable of. The whole chapter is dedicated to an interactive example that uses a wide variety of different jQuery methods and functionality, and the accompanying text gradually picks apart all of the code to show what it does. The example is excellent for those new to jQuery and was a very good way to start the book.

After the initial example-based chapter the book switches tone to more of a reference style guide; chapter 2 is a very detailed, quite lengthy chapter that covers all of the different types of selectors that can be used to select elements from the DOM. Many different selectors, including advanced ones like the different types of attribute selectors are covered.

Remaining chapters look at the different types of methods that are exposed by the library; there is a chapter dedicated to DOM traversal methods, another that looks at AJAX-related methods, etc. Helpfully, the book is structured similarly to the online documentation so readers should be able to easily find the method they require information about without too much difficulty.

Towards the end of the book there are chapters that look at the miscellaneous methods such as .grep(), .unique(), etc which don’t fit neatly into any of the other categories, and the different properties of the jQuery object that can give us extra information about the environment that the library is executing in such as the .browser properties. These last chapters will be of huge importance to many developers that are familiar with some of the more common methods, but less familiar with some of these lesser-used methods and properties.

There is also a chapter dedicated to the construction of jQuery plugins; the authors didn’t have to include an entire chapter on this topic as it is sometimes seen as beyond the scope of general jQuery usage. They could have just included some basic information under the miscellaneous chapter perhaps, but they didn’t, they provided a whole chapter to it because the topic deserves a whole chapter. It’s a relatively short chapter, and the example plugins are very light, but it covers all of the essentials for plugin development such as the standard conventions, the object method and global functions, so this chapter adds a lot of value.

The book also features some potentially very useful appendices including lists of useful tools for JS developers such as code minifiers and browser development tools, information about where to find useful JavaScript, (X)HTML and CSS references as well as a complete alphabetical listing of every jQuery method and property.

Overall, I found this an excellent reference book for developers of all levels and would recommend it to anyone that was serious about jQuery development. Bear in mind that it is a reference manual opposed to a recipe-style example-based book, so the style is very concise and sometimes dry. Personally I think this was a good thing as it allowed the book to remain focused on the core topics without going off on a tangent about implementational specifics that the reader may never encounter. It’s highly accessible, very information-heavy and literally covers every single method and property found in the library. This book will stay on my desktop (my real, actual desk) for some time to come and will remain my first point of contact from now on when looking up any method of the library.

My one complaint is that some of the appendix items from previous versions of the book seem to have been removed; for example, there is an information box in one chapter which states ‘An in-depth discussion of closures can be found in Appendix C of the book Learning jQuery 1.3.’ I’m sure many people buying the 1.4 version of the book won’t already have the previous edition so this is not helpful in any way. Leaving this non-essential but related information in the book would have been far better. Sometimes however, due to the limits that are placed on page count by publishers, old, less-related information has to be removed. It’s not a massive complaint, and I can understand why the authors may have had to remove these extras to make room for information relating to all the cool new functionality of jQuery, but I think the book would have benefited from retaining this information if at all possible.

Buy the book!

Better Password Fields with jQuery

February 8, 2010

The ‘whether or not to show plain text in password fields for usability’ situation has never really been resolved to my satisfaction; plain-text fields are clearly much more usable and less confusing than obscured passwords, but what if the person using the plain-text field is sat in a public place? Showing their password for just anyone to see would be ludicrous.

The iPhone style of obscuring everything except the last letter is a good compromise that offers a combination of security and usability, and there are plenty of great guides out there on how to implement this in your web pages.

But it’s still based on the flawed assumption that the user is always going to be somewhere public. And it’s not 100% secure anyway because if someone watches each letter as it’s typed over your shoulder, depending on what the password is, it could be very easy to remember. The point is that we don’t have to rely on a compromise when a solution is easy to implement.

The solution is to hand the initiative over to the visitor and let them decide for themselves whether to show the password in plain text or not. Then we don’t have to either use a semi-hidden, semi-secure way of presenting the field, and we don’t have to make the choice of whether to show plain or obscured text. All we need to do is add a simple link after the password field which will convert the obscured password field to a standard text field, thus revealing the password.

The code

Start off with the standard HTML that you would normally use when requiring a visitor to enter their password, probably something like the following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Better Password Fields</title>
  </head>
  <body>
    <form action="#" method="post">
      <label for="pass">Password:</label><input id="pass" name="pass" type="password">
    </form>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

    </script>
  </body>
</html>

The password field is specified as a password field so that if the visitor has JavaScript disabled the field will be obscured by default – better to err on the side of caution right?

We haven’t hardcoded a link to the page that will convert the password field into a plain text field; if JS is disabled the link will be completely useless. The best way to have an element on the page that requires JavaScript be enabled for it to work is to add the element with JavaScript in the first place – that way if JavaScript is disabled, the useless link won’t be added.

That’s all of the underlying HTML that we need – nothing more and nothing less, the very definition of semantic. Everything else we need we can add using the script, which we’ll look at next.

Preparing the form for revealed password fields

Let’s setup the initial part of the script which would run on page load; we left an empty script element at the bottom of the HTML, add the following code to it:

(function($) {
  $("form").find("input[type='password']").each(function(val) {
    var input = $(this);

    //insert link to show plain-text
    $("<a>").text("Show password").addClass("show-plain").attr({
      title: "Show the password in plain text",
      href: "#"
    }).insertAfter(input);
  });
})(jQuery);

All of our code will reside within a self-executing anonymous function which we pass the jQuery object into. Our function accepts the jQuery object using the $ parameter so it is safely aliased within the local scope of our function, which should offer protection from any other libraries that may be in use on whatever pages the code ends up on.

All we need to do at this stage is prep our password fields by adding the ’show plain text’ links after each password field. We first select all of the input fields that have a type of password (that’s just one in this example, but there could be more on pages out in the wild), then for each of the selected elements we create a new anchor and insert it directly after the current input field.

The new anchor has its title and href attributes set (some browsers won’t treat it as a link if it doesn’t have a href), and we give it a class name of show-plain (mostly so that we can select it in just a moment but potentially also for styling purposes).

Our page should now look like this, with the new link directly after the password field:

Better Password Fields 1

A simple, unassuming link. Next we need to make our new link(s) work; directly before the last line of code (})(jQuery);) add the following:

//add click handler for show-plain link(s)
$(".show-plain").live("click", function() {

  //cache selector
  var input = $(this).prev();

  //create new text input
  $("<input>").attr({
    id: input.attr("id"),
    type: "text",
    name: input.attr("name")
  }).val(input.val()).addClass(input.attr("class")).insertAfter(input.prev());
  input.remove();

  //change link text and attributes
  $(this).text("Hide password").removeClass("show-plain").addClass("show-hidden").attr({
    title: "Obscure the text"
  });

  //stop link being followed
  return false;
});

We use the live() method to add a click handler for the ’show plain text’ link because, as you can probably tell from the code above, the class name of the link changes. Using live() means that we don’t have to re-bind the click event every time we create a new link; the live() method uses event delegation which attaches a listener for this event to the specified element’s parent instead of binding directly to the element itself.

Within the anonymous function added as a parameter to the live() method we first cache a reference to the input element directly before the link that was clicked, so the variable will always refer to the correct input element regardless of which link is clicked. We cache it because we’ll be referring to it several times and we don’t want to have to select it from the document each time we want to do something with it.

Next we create our replacement text input, which we set to a standard text type so that its contents will be clearly visible. We copy any text that has already been entered into the password field, and any class names that may have been given to it. We then insert the new text field and remove the password field. It’s the old switcheroo, plain and simple, but it will look as if any text already entered into the password field is magically revealed. The following image shows the two states:

Better Password Fields 2

Reapplying the obscured text

Now we just need to add the code that will turn the revealed text back into obscured text, just in case the visitor needs to hide the password again. We’ve given the choice back to the visitor of whether the password should be visible or not, but we’d better give them the choice to hide it again too. After the click handler for the show-plain link add the following code:

//add click handler for show-plain link(s)
$(".show-hidden").live("click", function() {

  //cache selector
  var input = $(this).prev();

  //create new password input
  $("<input>").attr({
    id: input.attr("id"),
    type: "password",
    name: input.attr("name")
  }).val(input.val()).addClass(input.attr("class")).insertAfter(input.prev());
  input.remove();

  //change link text and attributes
  $(this).text("Show password").removeClass("show-hidden").addClass("show-plain").attr({
    title: "Show the password in plain text"
  });

  //stop link being followed
  return false;
});

This is pretty much the reverse of what we did in order to show the text; we just remove the plain text field, copying its value, id and any class names, and then replace it with a new input of type password. We also adjust the link again to reflect the new state. We should find that when we load the page we can enter text into the field and switch between plain and obscured text as in the previous screenshot in any common mainstream browser.

Summary

In terms of usability nothing can be better than giving your visitors a clear and simple choice; in this case whether or not to show a password in plain text or obscured text. We saw how easy it was to add this simple solution to a page – just a couple of lines of code. So instead of offering a compromise we can offer a solution, and improve the usability and effectiveness of password fields on our sites at the same time.

  • YUI 2.8: Learning the Library

    YUI 2.8

    The beginner to advanced-level guide for understanding the YUI library£46.98£41.33!read more
  • jQuery UI 1.7: The User Interface Library for jQuery

    jQuery UI 1.7

    Learn the latest version of jQuery UI with a detailed, step-by-step approach£29.99£23.79!Read more
  • jQuery UI 1.6: The User Interface Library for jQuery

    jQuery UI 1.6

    If you need to use jQuery 1.2, this book will show you how to leverage jQuery UI 1.6£29.99£23.79!Read more
  • Learning the Yahoo! User Interface Library

    Learning YUI

    Discover how to use version 2 of the YUI to it's full potential£27.99£23.79!Read more