Advertisement

Implementing the Float Label Form Pattern

by

Using Matt Smith’s mobile form interaction design as a guide, we will create a stunning form interaction for the web that’s both beautiful and accessible using HTML, CSS and JavaScript.


Overview

Form design and interaction on the web can be a sensitive subject. A multiplicity of form accessibility concerns and best practices can make designing a compelling form interaction very difficult, as opposed to form design on native platforms.

Matt Smith recently created a compelling form interaction he posted to Dribbble:

Take a look at the original Dribbble shot on floatlabel.com
Take a look at the original Dribbble shot on floatlabel.com

Though designed for a native iOS application, this form interaction can be recreated for the web using HTML, CSS, and Javascript while also appeasing form accessibility concerns.

The float label concept has stirred up quite some attention, leading to discussion and experiments all across the web.

Rather than use the same form fields in Matt’s design, we will create a simple contact form you could use on your own website. So let’s dive in!


Form Anatomy

First, let’s observe and record the form interactions Matt has created. This will allow us to predetermine how our form should be marked up. It will also give us a good understanding of how to style the form and create its interactions with JavaScript.

Form Structure

The form has the following elements we can translate to HTML:

  • <label> elements
  • <input> elements
  • <textarea> element
  • placeholder attributes
form-elements

Form Element Interactions

By observing the interactions Matt has created, we can formulate rules for the interaction of the form elements we will be creating. These rules will be useful in creating our markup, style rules, and JavaScript interactions.

  • on page load:
    • <label> elements
      • Hidden, emphasized with a highlight color.
    • <input> & <textarea> elements:
      • Show the element’s placeholder text.
  • on focus:
    • <label> elements
      • If the label’s corresponding input field is empty, hide the label. Otherwise, de-emphasize the label’s color.
    • <input> & <textarea> elements:
      • If the field is empty, show the element’s placeholder text. Otherwise, show the text entered by the user.
  • on keyup:
    • <label> elements
      • If the label’s corresponding input field is empty, hide the label. Otherwise, show the label.
    • <input> & <textarea> elements:
      • If the field is empty, show the placeholder text. Otherwise, show the text entered by the user.
  • on blur:
    • <label> elements
      • If the corresponding input field is empty, hide the label. Otherwise, de-emphasize the color.
    • <input> & <textarea> elements:
      • If the field is empty, show the placeholder text. Otherwise, show the text entered by the user.

Now that we have determined the form’s HTML elements along with its interaction rules, we can begin creating it.


Basic HTML

Let’s start by getting some basic starter code.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Contact Me</title>

    <!-- Viewport tag to make things responsive -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <!-- Link to the stylesheet we will create -->
    <link rel="stylesheet" href="styles.css">

    <!-- HTML5 shiv for older browsers -->
    <!--[if lt IE 9]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>

    <!-- Form Markup Will Go Here -->

    <!-- Google's hosted version of jQuery -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    <!-- Link to the javascript file we will create -->
    <script src="scripts.js"></script>
</body>
</html>

Creating the Form Markup

Now let’s create the markup for our form:

<section class="container">
    <h1 class="title">Contact Me</h1>
    <form id="form" class="form" action="#" method="get">
        <ul>
            <li>
                <label for="name">Your Name:</label>
                <input type="text" placeholder="Your Name" id="name" name="name" tabindex="1"/>
            </li>
            <li>
                <label for="email">Your Email:</label>
                <input type="email" placeholder="Your Email" id="email" name="email" tabindex="2"/>
            </li>
            <li>
                <label for="message">Message:</label>
                <textarea placeholder="Message…" id="message" name="message" tabindex="3"></textarea>
            </li>
        </ul>
        <input type="submit" value="Send Message" id="submit"/>
    </form>
</section>

Here we setup a form container with a header of “Contact Me” and the corresponding form elements structured within list elements. Notice we also assigned the email field type="email". This provides contextual virtual keyboards for devices that support them as well as simple, browser supported validation for those browsers that support HTML5 input types. For those that do not, it becomes a simple text field.

What we have now are the very basics of a form that will work anywhere and is properly structured for simple accessibility.

basic-form

Note: We are not covering server side form submission in this tutorial, so feel free to change the form’s submission method as needed.


Creating Basic Page Styles

We now have a working form in HTML. Now we are going to make our first step in progressive enhancement: applying CSS styles. Let’s create styles to make our form more visually appealing while also remembering to keep the form functional and accessible.

Let’s create some basic styling for the page and form container. In the <head> of our document we created a link to a file named styles.css, so we will create that file now and save it to the root of our project.

We begin by importing the styles from Eric Meyer’s CSS reset into our own file. You can grab those styles here and copy them into your own style sheet.

Next, let’s create some general page styles:

/* General
==================================== */
*, *:before, *:after {
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    box-sizing: border-box;
}

body {
    background: #eaedf1;
}

body, input, textarea {
    font: 1em/1.5 Arial, Helvetica, sans-serif;
}

.container {
    max-width: 25em;
    margin: 2em auto;
    width: 95%;
    
}

.title {
    font-size: 1.5em; 
    padding: .5em 0;
    text-align: center; 
    background: #323a45;
    color: white;
    border-radius: 5px 5px 0 0;
}

You’ll notice we use Paul Irish’s suggested approach to the box model when styling forms: box-sizing: border-box;.

Now we have something somewhat better, but it’s going to need some more work.

basic-form-styles

Creating Form List Styles

Let’s apply some styles to our form elements. These will make our form look more similar to Matt’s.

First, we will style the list elements that contain our form elements.

/* Form
==================================== */
.form ul {
    background: white;
    margin-bottom: 1em;
}

.form li {
    border: 1px solid #ccc; 
    border-bottom: 0;
    margin-bottom: 0px; 
    position: relative; 
}

.form li:first-child {
    border-top: 0;
}

.form li:last-child {
    border-bottom: 1px solid #ccc;
}

Now we have all our form elements visually contained. You should have something like this:

basic-form-list-styles

Creating Form Element Styles

Let’s continue styling our form elements to match Matt’s design while also taking into account the accessibility constraints of the web.

Style the input fields as big block-level elements in the form:

label, input, textarea {
    display: block; 
    border: 0;
}

input, textarea { 
    width: 100%; 
    height: 100%; 
    padding: 2.25em 1em 1em; 
    outline: 0;
}

textarea {
    height: 16em;
    resize: none; 
}

You should have something like this:

form-input-styles

Then style the form <label> elements to sit positioned about one-third of the way from the top of each input block.

label {
    font-size: .8125em; /* 13/16 */ 
    position: absolute; 
    top: 1.23em;
    left: 1.23em;
    color: #f1773b;
    opacity: 1;
}

Note: did you notice the opacity rule? We will be using that property (along with the top property) to animate the <label> element later on using JavaScript.

You should have something that’s starting to look a lot like Matt’s form design.

form-label-styles

Next, need to style our form submit button.

input[type="submit"] {
    background: #f1773b;
    margin-bottom: 1em;
    color: white;
    border-radius: 3px;
    padding: .75em;
    -webkit-appearance: none; /* remove default browser <button> styling */
    -webkit-transition: .333s ease -webkit-transform;
    transition: .333s ease transform;
}
input[type="submit"]:hover {
    -webkit-transform: scale(1.025);
    transform: scale(1.025);
    cursor: pointer;
}
input[type="submit"]:active {
    -webkit-transform: scale(.975);
    transform: scale(.975);
}

Notice we used the attribute selector to target only the submit button. We added some basic styles along with a simple interaction on the :hover and :active states (older browsers that do not support CSS transforms simply will not have a fancy interaction, but the form still works). You should now have something like this:

form-submit-styles

Our form has been styled in a way that is similar to Matt’s design but also tailored to appease the accessibility concerns of the web. Notice how, without any JavaScript, the form is still accessible with the form fields being displayed at all times. For users with older browsers that do not support the placeholder attribute, they will still be able to see the form fields and ascertain what information is required of them.

In addition, the <input> and <textarea></textarea> elements cover the entire form field block, so the target area for each input is quite large and accessible.

For example, this is what the form would look like at this point in Internet Explorer 8:

form-ie

Using JavaScript for a Progressively Enhanced Form

We shold now begin thinking about how to implement the interaction Matt created using JavaScript. We’ll accomplish this largely by adding and removing CSS classes.

You will notice right before the closing <body> tag we put a link to our custom JavaScript file named scripts.js. We can create that file now and tell the browser to run the code when the DOM is ready:

$(document).ready(function(){
    // Our code here
});

Checking for placeholder support

In case you haven’t noticed, this interaction is highly dependent on placeholder support. The placeholder attribute is widely supported in modern browsers. Because our form interaction is so dependent on placeholder support, we will first test to see if the browser supports placeholder text. If it does, we will implement the form interaction. If it doesn’t (IE8 & IE9) we will simply provide the basic form without JavaScript interaction. Progressive enhancement for the win!

First, let’s use jQuery’s $.support() to see if the browser supports placeholder text. This will set $.support.placeholder to true or false, depending on the browser’s support for placeholder text.

// Test for placeholder support
$.support.placeholder = (function(){
    var i = document.createElement('input');
    return 'placeholder' in i;
})();

If placeholder text is supported, we can hide the <label> elements on page load. As mentioned before, hiding the labels with JavaScript after the page loads ensures that browsers with JavaScript turned off (and those without placeholder support) can still use the form.

// Hide labels by default if placeholders are supported
if($.support.placeholder) {
    $('.form li').each(function(){
        $(this).addClass('js-hide-label');
    });  

    // Code for adding/removing classes here
}

Notice that we added a class to each list item named js-hide-label. This is because, as per the interactions rules at the beginning of the tutorial, the default appearance of the form has the form field labels hidden. The js-hide-label class will be applied to parent <li> elements when the descendant <input> element is empty of user content.

To aid in comprehension and code maintainability, we are prefixing the classes we add or remove with JavaScript with 'js-'. Let’s add that class to our style sheet and use it to hide all descendant label elements from view. Remember how we were going to using the opacity rule? This is where we use it to hide the <label> elements:

.js-hide-label label {
    opacity: 0; 
    top: 1.5em
}

Note: The opacity property is supported in all modern browsers. IE8 will not recognize it, but that’s ok because IE8 does not support placeholder attributes either, so we are not actually running the JavaScript to apply the class in IE8. Win-win!

A Note on Transitions

If you observe closely, Matt’s interaction design shows the form field labels not only appearing and disappearing, but doing so with a little up and down movement. Because our label elements are positioned absolutely, when we add a class that changes it’s top positioning (or left, right, or bottom) the browser can transition that effect. All we have to do is add a transition property to the label itself.

Let’s go back to our label element in the CSS and add a transition property for the top and opacity properties:

label {
    -webkit-transition: .333s ease top, .333s ease opacity;
    transition: .333s ease top, .333s ease opacity;
}

This allows the labels to not only appear and disappear smoothly, but to bobble up and down when becoming fully opaque or transparent, like so:

form-hiding-label

You should now have something like this when you load the page (in a modern browser of course).

form-hidden-labels

Removing the Highlight Color

As mentioned before, we are adding and removing classes from the <li> elements and targeting any children that need styling. At this point (on page load) we have added a class of js-hide-label that hides all labels in the form. Now we need one more class for removing the highlight color from the <label> elements:

.js-unhighlight-label label {
    color: #999 
}

Adding Event Listeners

Now we have a form that is progressively enhanced and ready for some JavaScript interaction (in modern browsers) when the user begins interacting with the form.

Inside the placeholder if statement we wrote above, let’s start adding and removing our js- classes at the right moment. First, we will select our form elements and add an event listener on the blur, focus, and keyup events (we use keyup rather than keydown or keypress as those events will fire prematurely):

$('.form li').find('input, textarea').on('keyup blur focus', function(e){
    
    // Cache our selectors
    var $this = $(this),
        $parent = $this.parent();

    // Add or remove classes
    if (e.type == 'keyup') {
        // keyup code here                    
    } 
    else if (e.type == 'blur') {
        // blur code here
    } 
    else if (e.type == 'focus') {
        // focus code here
    }
});

Here is a brief explanation of what we are doing here:

  • We select all list items that are part of our form $('.form li'). Then, inside that selection, we find all <input> and <textarea> fields .find('input, textarea'). This ensures that the last input in our markup (the submit button) is not included in our selection.
  • We cached the selectors we plan on using. This is a good performance practice. Also, prefixing the variable name with '$' lets us know that that specific variable is a jQuery object.
  • We combined the blur, focus, and keyup events and simply check the event type using e.type to determine which classes we’ll be adding or removing at specific moments.

Coding on keyup

According to the interaction rules we laid out at the beginning which correspond to Matt’s design, when a user starts entering text (not when they focus on the field) we want to show the label.

So, using the keyup event, every time the user enters a character we can check to see if the input field is blank (this code goes inside if(e.type == 'keyup'):

if( $this.val() == '' ) {
    $parent.addClass('js-hide-label'); 
} else {
    $parent.removeClass('js-hide-label');   
}

Notice our logic works like this:

  • If the input’s value is blank, hide the label by adding the 'js-hide-label' class.
  • Otherwise (the input’s value is not blank), show the label by removing the 'js-hide-label' class.

You should now have something that works like this when you enter or delete text from an input field:

form-hiding-label

Coding on blur

Now, according to our interaction rules (again), we know that when a user moves the focus from one input field to the next (blur event), we should de-emphasize the color of the <label> element depending on whether the user has actually entered anything into the field.

Inside the else if (e.type == 'blur'), we will add the following code:

if( $this.val() == '' ) {
    $parent.addClass('js-hide-label');
} 
else {
    $parent.removeClass('js-hide-label').addClass('js-unhighlight-label');
}

Notice our logic works like this:

  • If the input’s value was blank when the user removed focus, hide the label by applying the js-hide-label class.
  • Otherwise (the input’s value was not blank when the user removed focus) show the label by removing the class js-hide-label and de-emphasize the label's color by adding the 'js-unhighlight-label' class.

You should now have something that de-emphasizes the label’s color when you remove focus, like this:

form-blur

Coding on focus

Last of all, we need to add a little logic for when a user focuses on an input. Following our interaction rules, let’s use the following JavaScript inside the else if (e.type == 'focus') section:

if( $this.val() !== '' ) {
    $parent.removeClass('js-unhighlight-label');
}

Our logic works like this:

  • If the input’s value is not blank, remove the parent’s 'js-unhighlight-label' class.

Now when a user focuses on a form field, if it’s not empty, the label will be emphasized with the highlight color, like so:

form-focus

Bonus Points

There is a lot more we could do to this form, including the addition of client- and server-side validation. We could also create a few more classes for styling valid and invalid field values. For example, we could add styles to a class of 'js-error' which would go on the parent <li> element when the input’s value is invalid, like so:

.js-error {
    border-color: #f13b3b !important; /* override all cases */
}
.js-error + li {
    border-top-color: #f13b3b;
}
.js-error label {
    color: #f13b3b;
}

These types of validation styles could make our form look something more like this:

bonus-form-error

However, this tutorial was meant to show how we could create an accessible, progressively enhanced form mimicking Matt’s design. And, I have to say, I think we have done pretty well.

Feel free to copy, modify, or improve this form in anyway you see fit in your own projects!


Useful Links

Advertisement