Feature Detect Placeholder to Adjust jQuery Mobile Layout

If you take a look at most of the jQuery Mobile Documentation you will see heavy use of labels and input elements inside of a fieldcontain data-role. The great thing about this technique is that it looks good on portrait layouts (labels on top & input on bottom) and also adjusts for landscape layouts (labels on the left & input on the right).



The HTML to generate the above screenshots can be found in the following markup.

 



Acme Corporation








name="email" class="required email" />




name="password" class="required" />


















I recently did a mock-up for a client using this technique, but they wanted to use the HTML5 form placeholder technique instead. I told the client that this was possible, but mentioned that not all browsers support this technique.

So, I decided to use a Progressive Enhancement approach to this problem using the Modernizer JavaScript library. I wrote some JavaScript to detect if the browser supports the placeholder HTML5 attribute and if it does, then I hide and take the text from the label element and then push the value into the input element's placeholder attribute.

 
// if placeholder is supported
if ( Modernizr.input.placeholder ) {

$( "input" ).each( function(index, element) {

var placeholder =
$("label[for=" + element.id + "]")
.hide().text();

$(element)
.addClass("ui-input-text-placeholder")
.attr("placeholder", placeholder);

});

}

You can view a running example of the above code from this jsFiddle. If you are running Google Chrome, then you'll notice the label's are embedded as placeholder's within the input elements, but if you are using Firefox or Internet Explorer 6/7/8 then you'll notice the default label and input technique that is default in most of the jQuery Mobile documentation.



I've added some screenshots of the placeholder technique in case you are reading this blog entry in a browser that doesn't support the HTML5 form placeholder attribute.