·

photo credit: Halloween bokeh delux! via photopin (license)

Simple Focus labels with Knockout

A couple of days ago I wrote a small article about how to create simple focus labels with JavaScript. For those who havent read that article, it’s how to create form elements with placeholders that transform into labels:

Screen Shot 2015-12-03 at 19.47.45
In this article, I’ll do the same thing, but with Knockout components.

Knockout components

For those who don’t know what Knockout components are: they are a nifty little tool to create re-usable chunks of HTML in a simple way (like UI elements for example). They consist of a template and a piece of JavaScript that utilizes the data-binding functionality of Knockout.
Since our ‘focus labels’ are a typical example of such a re-usable UI element, the use of a Knockout component is a good choice for this.

The Component JavaScript

The complete JavaScript looks as follows:

Let’s break it down piece by piece:

  1. At first, we register a component called ‘focuslabel’. This means we can use a custom tag <focuslabel params=”…”></focuslabel>  anywhere in our HTML to create an instance of our component.
  2. At the start of our view model, we retrieve and sanitise the parameters that we get from our element. We set our name, label and value. If there are no label or value set, we create a default value.
  3. The model has one observable: this.focused() . This parameter is used to set an ‘active’-class on our wrapping element. See the template for more detail.
  4. Then we have 2 methods: this.focus()  and this.blur() . These methods are used to set the value of our this.focused() -observable.
  5. The template we create is very simple. It consist of a wrapping <span> -element, containing a <label>  and an <input> -element. Let’s break it down:
    1. The <span> -element has a data-binding that sets or removes the ‘active’-class according to the value of our this.focused() -observable.
    2. The content of the <label> -element is set from the variable this.label .
    3. The <input> -element has the most data bindings:
      1. It’s attribute is set according to the variable this.name .
      2. It’s (initial) value is set according to the variable this.value .
      3. It’s focus- and blur events are bound to it’s corresponding methods in the view model.

It might seem complex, but it’s actually pretty easy.

The HTML

The HTML code we use is pretty straight forward as well:

As you can see, we use our custom <focuslabel> -element to create instances of our component. We use the params -attribute to set our parameters, such as the name, the label or the initial value. There’s really nothing more to it than this.

The result

The end result can look something like this:

See the Pen Focus Labels with Knockout by Giel Berkers (@kanduvisla) on CodePen.

Visitors give this article an average rating of 4.7 out of 5.

How would you rate this article?

Leave a Reply