Inputs with Floating Labels to Make Forms Look Better

Posted By Vijendra Kumar | 28-Feb-2018

In recent months there has been much discussion on the use of tags in the discussion of accessibility, which I think is fine. Web designers and developers should make accessibility an essential part of development, not as a last-minute idea.

 

Still, I found a lot of more practical solutions for ignoring tags, which in turn created accessibility issues. Interestingly, there are many existing models that are friendly to design and use tags. A label that has existed for several years is a floating label:

 

It's easy to implement with a few CSS and jQuery.

 

The markup:

Suppose we need to create a registration form as described above. We will start with the first entry and label:


 

The CSS

Entries and labels are wrapped in a container class so that the tag's interaction is at the entrance:

.field {
  position: relative;
}

The label selector will be defined with this basic ruleset:

label {
  left: .5em;
  opacity: 1;
  position: absolute;
  top: .25em;
  transition: all 0.1s linear;
}

The initial position of the label will be "inside" the input element (in fact, it's just at the top). We want to convert the position of the label when the input has the focus, so it moves above the entrance:

 

input:focus + label,
input + label.show {
  color: #2ea8c5;
  font-size: 1.15em;
  left: .75em;
  opacity: 1;
  top: -1em;
}

The .show class will be used by our jQuery code, so let's start with this.

The jQuery

First, let's create a function and add a variable to the ".show" class:

$(function () {
  let showClass = 'show';
});

Next, we will add an internal function to check if "<input>" is empty:

$(function () {
  let showClass = 'show';
  
  $('input').on('checkval', function () {
    let label = $(this).next('label');
    if(this.value !== '') {
      label.addClass(showClass);
    } else {
      label.removeClass(showClass);
    }
  })
});

If the entry has a value, the ".show" class will be added to the label so it is above the entry.

 

Finally, we will include an event detector that validates the value of "<input>" when the user enters a character:

$(function () {
  let showClass = 'show';
  
  $('input').on('checkval', function () {
    let label = $(this).next('label');
    if(this.value !== '') {
      label.addClass(showClass);
    } else {
      label.removeClass(showClass);
    }
  }).on('keyup', function () {
    $(this).trigger('checkval');
  });
});

 

Request for Proposal

Recaptcha is required.

Sending message..