Aug 09, 2010

jQuery Show Password Plugin

In a recent project at work, I had to add in functionality so that a user could see what they had typed in a password field when they click a link. One would think that it is as easy as using JavaScript to change the type attribute, but that of course doesn’t work in IE. Virtually all of the jQuery plugins that I found used a checkbox instead of a link to toggle between the two states. So, I set out to write my own.

If you just want to get to the code, you can download the plugin from GitHub or check out the demo.

This plugin works by adding a text field that takes the value of what is typed into the password field. Then, when the link is clicked the password field is hidden and the text field is shown.

The Markup

In the demo, we’ll just start with a simple form:

<form action="#">
	<ol class="forms">
		<li>
			<label for="username">Username</label>
			<input type="text" id="username" />
		</li>
		<li>
			<label for="password">Password</label>
			<input type="password" id="password" class="password" />
		</li>
		<li class="buttons">
			<button type="submit">Submit</button>
		</li>
	</ol>
</form>

Add a Little Style

In the design that I was working on, the link to show the password actually sat on top of the password input field, so we just need to add a little bit of CSS to make that happen:

.forms li {
	position: relative;
}
.show-password-link {
	display: block;
	position: absolute;
	z-index: 11;
}
.password-showing {
	position: absolute;
	z-index: 10;
}

By default, the link to show the password has the class of show-password-link, but that can be changed in the plugin options. Also, the password-showing class is added to the text field that is used to show the password, but again, that can be changed via the plugin options.

And Now, JavaScript Takes Over

To get started, you will need to include jQuery and my plugin:

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.showPassword.min.js"></script>

Then, you can instantiate it like this:

$(document).ready(function() {
	$(':password').showPassword();
});

Options

So there you have it. Check out the demo and download the plugin from GitHub.

Categories