Robert Robert - 1 year ago 62
Android Question

Any way to use JavaScript to *not* set focus on any HTML element?

I have a mobile signup form that contains HTML input elements for the user's username, password, and password confirmation fields. Since this is a mobile web app and I'm trying to conserve screen space, I've elected to forego putting HTML labels above each of these elements and instead utilize placeholder attributes to signal what to enter in each field:.

<input id="id_username" placeholder="Choose a username" type="text" />
<input id="id_password1" name="password1" placeholder="Choose a password" type="password" />
<input id="id_password2" name="password2" placeholder="Confirm password" type="password" />

Initially I added a bit of JavaScript to put the focus on the username field when the user arrives at the page:

<script type="text/javascript">

This worked fine except that in older versions of the default Android browser, this causes the placeholder to disappear. Since the lack of a placeholder (and label) may cause the user to not be clear on what to enter in that field, I took the JavaScript out. However, even without that JS, I'm noticing that the Android browser still puts the focus in that first form field which again deletes the label. Is there any way that I can code the page so that I'm guaranteed that no browser (including the default Android browser) will put focus on any of these fields? Techniques that wouldn't require additional libraries would be preferable as I'm trying to keep my page size and additional requests to a minimum.


Answer Source

Sometimes it is faster to write some simple functionality by your hands. Look at the example at js fiddle. If you want you can replace jquery with native javascript.

var placeholder = 'enter something';
$(document).ready(function() {
    $('.placeholder').focusin(function() {
    if($(this).val() == placeholder && $(this).hasClass('opacity')) {
  $('.placeholder').focusout(function() {
    if($(this).val() == '') {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download