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).


<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>

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit