Floaters

Input labels

by Sabazou

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<form>
    <input type="text" class="-floaty-input" placeholder="Type something..." id="floaty" />
</form>

CSS

.-floaty-container {
    position: relative;
}

.-floaty-input,
.-floaty-label {
    color: #ccc;
    font-size: 11px;
    line-height: normal;
}

.-floaty-container input:focus {
    color: #333;
}

.-floaty-hide-label .-floaty-label {
    opacity: 0;
}

.-floaty-label {
    cursor: text;
    display: block;
    left: 7px;
    opacity: 1;
    position: absolute;
    top: 0;
    -webkit-transition: opacity .1s linear;
}

JavaScript

(function (window, doc, $, undefined) {
    
    var ceil = Math.ceil,
        floor = Math.floor;

    var Floaty = function (element, options) {
        if (this.assembled) {
            return this;
        }

        this.assembled = false;
        this.input = element;

        // Reset existing placeholder attribute
        this.placeholder = this.input.getAttribute('placeholder');
        this.input.setAttribute('placeholder', '');

        this.assemble();
        this.bindEvents();

        this.assembled = true;

        return this;
    };
    
    Floaty.prototype = {
        constructor: Floaty,
        createContainer: function () {
            var container = document.createElement('div')
            container.className = '-floaty-container';

            return container;
        },
        createLabel: function () {
            var label = document.createElement('label');
            label.className = '-floaty-label';
            label.setAttribute('for', this.input.id);

            var labelText = doc.createTextNode(this.placeholder);
            label.appendChild(labelText);

            return label;
        },
        bindEvents: function () {
            var keyTimer, container = this.container;

            // Applies the -floaty-hide-label class to the container
            // if the input is not empty
            this.input.onkeydown = function () {
                var self = this;

                clearTimeout(keyTimer);
                keyTimer = setTimeout(function () {
                    console.log(self.value.length)
                    if (self.value.length > 0) {
                        container.classList.add('-floaty-hide-label');
                    } else if (self.value.length === 0) {
                        container.classList.remove('-floaty-hide-label');
                    }
                }, 1);
            };
        },
        assemble: function () {
             // Create a new floaty container
           ...