SO - 22745699

by Emily Humphrey

HTML

<div id="page-contain">
    <div class="contain">
        <form class="contact-form">
            <input type="text" id="contact-name" class="float" value="Name">
            <input type="email" id="contact-email" class="float" value="Email">
        </form>
    </div>
</div>

CSS

.active-filled {
    color: green;
}
.active {
    color: blue;
}
.active-filled.active {
    background: lightblue;
}

JavaScript

var floatLabel = $(".float");

$(floatLabel).each(function () {
    var input = $(this),
        title = $(this).val(),
        id = $(this).attr("id"),
        label = "<label class='float-label' for='" + id + "'>" + title + "</label>";

    input.wrap("<span class='float-label-ctn'></div>");
    input.val("");

    var ctn = input.parent();

    $(label).insertAfter(input);

    input.focus(function () {
        var userText = input.val();
        ctn.addClass("active");
        if (userText === title) {
            input.val("");
        }
    });

    input.blur(function () {
        ctn.removeClass("active");
    });

    var timer;
    input.keyup(function () {
        ctn.addClass("active-filled");
        var userText2 = input.val();
        console.log(userText2);

        clearTimeout(timer);
        timer = setTimeout(function () {
            if (userText2 === "") {
                ctn.removeClass("active-filled");
            }
        }, 50);

    });

    input.change(function () {
        var userText2 = input.val();

        if (userText2 === title) {
            ctn.removeClass("active-filled");
            input.val("");
        }

    });
});