Archive for the ‘jQuery’ Category
Better Password Fields with jQuery
February 8, 2010The ‘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:

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:

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.
Review of jQuery 1.3 with PHP by Kae Verens
January 31, 2010jQuery 1.3 with PHP by Kae Varens is a great book that shows you how to interface jQuery with PHP. It’s different from any other web development book I’ve read because it approaches things from the opposite perspective that I personally am used to – from the server to the client. It’s aimed at competent PHP developers that want to learn how to use jQuery. Strictly speaking I’m outside of the scope of who the book is aimed at, but fortunately I just enough PHP to follow along with the examples and know roughly what is happening in the server-side code. It is made clear very early on who the book is aimed at.
One thing that I really liked about this book was that as well as the strong focus on jQuery throughout (as you’d expect) the author also included not just one, but several different examples of using jQuery UI in conjunction with PHP. jQuery UI is the official UI library for jQuery so I think it’s important that it should be covered in this kind of book, even if only briefly.
The book is broken down into the following chapters:
Chapter 1 eases you into the book with sections on what jQuery is, why you should be using it and how it integrates with PHP. Some popular web applications that use jQuery are looked at and the author shows how to set up a directory structure so that the examples in the book can be replicated.
Chapter 2 covers some quick tips that server-side developers can use in order to help bridge the gap between the client and the server. Examples include how to make select boxes dynamically load options when required, contextual help tips, and inline editing of a page’s content.
Chapter 3 looks at the tabs and accordion widgets from jQuery UI and shows not only how to load their contents dynamically, but also how to create them on the fly with the server. This is a very thorough and detailed chapter and I really liked the code examples here.
Chapter 4 focuses on forms and form validation; it shows how to use the jQuery validation plugin in order to perform some validation on the client before involving the server (such as checking for empty fields which are required), and how to complete the validation on the server. Another code examples shows how to easily create an awesome auto-complete text-field.
Chapter 5 is another very thorough and in-depth chapter dominated by code examples; it shows how to create a file management system that allows for creating, moving and deleting directories on the server and uploading, moving and deleting files. This was probably my favourite chapter of the book.
Chapter 6 shows you how to create an entire calendar application that allows you to add, delete and move events and how recurring events can be handled. This is a great practical chapter that uses some interesting plugins including the jquery-week-calendar and the jQuery UI dialog. The example really highlights how to make these plugins work with server efficiently.
Chapter 7 covers image manipulation such as cropping, resizing and rotating. Jorn Zaefferer’s treeview plugin is used in conjunction with some of the file management app created in chapter 5 to show the images available, while the actual manipulations are performed with the ImageMagick PECL extension.
Chapter 8 looks at the client-side heavy jQuery UI interaction helper sortable; so far the jQuery UI components the book has looked at have all been UI widgets so it’s great that this is included as well. Drag and drop, a very client-side oriented task, is looked at in detail and there is probably less server-side code in this chapter than in any other, which must be incredibly useful for those more used to working with the server.
Chapter 9 looks at displaying large sets of tabular data efficiently and uses the dataTables jQuery plugin to allow pagination, sorting, filtering and column re-ordering. There are some interesting (for me) server-side concepts in this example such as caching and how to load data is small chunks, but a server-side developer would probably know this already. The client-side code examples were quite extensive as well though and would help server-side developers use the dataTable plugin effectively.
The final chapter, chapter 10 looks at a series of examples that show how client-side code can be optimised to improve the user experience; it’s a fast paced chapter with a lot of small examples and contains some real gems of information.
Overall this is a great book with very thorough and well-explained examples and plenty of code that the average server-side developer could take away and reuse. As a front-end developer I’m completely the opposite of who the book is aimed at but it was clear that the descriptions of using jQuery would be of value to PHP developers.
jQuery Plugin – jPoll
December 13, 2009jPoll, with an accompanying nettuts+ screencast, provides a ‘poll’ widget which can be used to ask your visitors a brief question. The widget will create and render a form inside a designated container and then monitor the form for submission.
When the form is submitted,the results are passed to a backend file which processes the response (I used PHP and MySQL, although other languages and database servers are available). The widget is just the frontend of the application, you must supply the backend.
Once the visitor’s choice has been saved, the results of the poll are then passed back to the widget as a JSON object and the widget displays the results using nice animations.
Example
Features
The first release of jPoll comes with the following features:
- Automatic error message for submission before choice is made
- AJAX sending and receiving of selection and results
- Built-in result animations
Usage
All you need to do on the webpage is supply a container element with an id:
<div id="container"></div>
Then in your script, just call the jPoll constructor supplying a literal configuration object containing the customised properties:
$("#container").jPoll({ ajaxOpts.url: "myBackend.php", groupIDs: ["A Question", "Another Question", "Etc..."] });
All of the properties have defaults, but some are fairly generic. The config section below shows all of the properties and their default values.
Note that this is just the front-end – you must have a database setup to store the results in and you need an accompanying PHP script that gets and set the results in the database.
Config
var config = {
ajaxOpts.url: "a string" //defaults to "poll.php"
groupName: "a string" //defaults to "choices"
groupIDs: ["an array"] //defaults to ["choice0", "choice1", "choice2", "choice3", "choice4"]
pollHeading: "a string" //defaults to "Please choose your favourite:"
rowClass: "a string" //defaults to "row"
errors: true || false //defaults to true
}
$("#container").jPoll(config);
jQuery Plugin – jMailer
December 13, 2009jMailer is a plugin for jQuery I wrote that provides the visitor with a popup email form. It should be attached to a link element and when that link is clicked, the popup appears centered in the viewport.
Within the popup is a form which let’s the visitor enter an email address they want to send the email to, their email adress so that the recipient can reply directly to them, a subject box and a message box.
jMailer Example
The ‘Contact Me’ tab at the top of this site has the plugin attached; click it to see the popup form and send me a message
The To field has been mapped to my own mail address in the back-end so messages will only come to me.
You should also note that the plugin constitues just the front-end. A back-end of your choice (PHP, .NET, etc) can be attached to do the physical sending of mail.
jMailer Features
The current release (1.1) of jMailer has the following features:
- Automatic modality
- Automatic iFrame shim when IE6 is used
- Configurable opening and closing animations
- AJAX sending of form data to the back-end and confirmation message
- Basic error checking for non-completed fields
jMailer Usage
Using the plugin is simple: Download the source file and ensure you have a copy of the jQuery library to hand (min version 1.2.6).
Then just attach the plugin to the link using standard jQuery syntax:
$("#mailerLink").jMailer();
jMailer Configuration
A configuration object can be supplied in the constructor to configure various options:
var config = {
modal: true || false //defaults to true
id: "a string" //defaults to "mailer"
shim: true || false //defaults to false unless IE6 in use
forceShim: true || false //defaults to false
defaultClass: "a string" //defaults to "mailer-container"
additionalClass: "a string" // defaults to null
suppressTo: true || false //defaults to false
animation: hide || slideUp || fade //defaults to hide
}
$("#mailerLink").jMailer(config);

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
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 YUI
Discover how to use version 2 of the YUI to it's full potential£27.99£23.79!Read more
