T
I have modified the Float Pattern Demo to work on a select box.
First things first, I added a State wrapper, label, and box to the HTML form with all the states in there as options. I included a default item with the text State and an empty string for its value. This way I could easily tell if it was selected vs an actual state option.
Next, I modified the CSS by putting in 2 styles. option { color: black; } and .watermark { color: #aaa }. The first one defaults the select options to black. The second one is used to change the option color to a gray, just like the watermarks on the other input elements, based on the default item being selected or not.
The last thing I had to do was modify the jQuery to hook up the select box. So the way this originally worked was that it bound a function called checkval that would toggle the visibility of the floating label and attached listeners to the keyup, focus, and blur events for all input elements.
I needed a way to hook in the select, so what I did was modify the selector to include select, so it becomes $("input, select"). The next thing I had to do was attach a specific listener for the select change event, as that's the one that gets fired when a selection has been made. Then all I had to do was write some code that would toggle off and on the watermark class I made earlier based on whether or not the currently selected item's value had a value or not. After that, it simply makes a call to the checkval function to toggle visibility on the select box's floating label.
I haven't tested it in all browsers, but seems to me that it's identical to the other floating labels and keeps the user experience consistent and clean.
Enjoy!
See working CopePen demo
HTML
First Name
Last Name
City
State
CSS
.field-wrapper
{
position: relative;
margin-bottom: 20px;
}
label
{
position: absolute;
top: -13px;
left: 0;
font-size: 11px;
color: #aaa;
transition: all 0.1s linear;
opacity: 0;
font-weight:b old;
}
label.on
{
color: #4481C4;
}
label.show
{
top: -15px;
opacity: 1;
}
option
{
color: black;
}
.watermark
{
color: #aaa;
}
body
{
padding: 20px;
/* the following line fixes a blink in chrome https://code.google.com/p/chromium/issues/detail?id=108025 */
-webkit-backface-visibility: hidden;
}
JQUERY
$(function ()
{
var onClass = "on";
var showClass = "show";
$("input, select")
.bind("checkval", function ()
{
var label = $(this).prev("label");
if (this.value !== "")
label.addClass(showClass);
else
label.removeClass(showClass);
})
.on("keyup", function ()
{
$(this).trigger("checkval");
})
.on("focus", function ()
{
$(this).prev("label").addClass(onClass);
})
.on("blur", function ()
{
$(this).prev("label").removeClass(onClass);
})
.trigger("checkval");
$("select")
.on("change", function ()
{
var $this = $(this);
if ($this.val() == "")
$this.addClass("watermark");
else
$this.removeClass("watermark");
$this.trigger("checkval");
})
.change();
});