Feature Detect Placeholder to Adjust jQuery Mobile Layout
09 Feb 2011If 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).
<div></div>
The HTML to generate the above screenshots can be found in the following markup.
<pre>
<div data-role="page" id="login">
<div data-role="header">
<h1>Acme Corporation</h1>
</div>
<div data-role="content">
<form id="frmLogin" class="validate">
<div data-role="fieldcontain">
<input type=âtextâ id=âemailâ
name=âemailâ class=ârequired emailâ />
</div>
<div data-role="fieldcontain">
<input type=âpasswordâ id=âpasswordâ
name=âpasswordâ class=ârequiredâ />
</div>
<div class="ui-body ui-body-b">
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<button id=âbtnCancelâ data-theme=âdâ
data-icon=âdeleteâ>Cancel</button>
</div>
<div class="ui-block-b">
<button id=âbtnLoginâ type=âsubmitâ
data-theme=âaâ data-icon=âcheckâ>
Log In
</button>
</div>
</fieldset>
</div>
</form>
</div>
</div>
</pre>
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.
<pre>
// 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);
});
}
</pre>
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.
<div></div>