Monthly Archives: February 2015

A hidden textbox that only appears when you need it

Sometimes you need to save screen real estate. One way to do that is to hide a text box when you don’t need it and make it appear when you do.

Suppose you have a search display. Generally, that consists of a text box and a search button like so

<input id="searchInput" type="text"/>
<button id="searchBtn">Submit</button>

Let’s first hide the search box

#searchInput {
  display: none;
  width: 0;  
}

Now, let’s set up the code that makes it appear when the mouse hovers over the search button. In addition, the search box should appear when the user clicks on the search button. Why? Because if the user is on mobile, then they can’t hover over a button without clicking on it.

function attachEventHandlersOnDocument {

  $('#searchBtn').on('mouseenter', that.showSearchInput);

  $('#searchInput').on({
    blur: function(evt) {
      if( !evt.relatedTarget
      ||  evt.relatedTarget.id != 'searchBtn' ) {
        that.hideSearchInput();
      }
    },
    keypress: function(evt) {
      if( evt && evt.keyCode == 13 ) {
        that.doSearch($(this).val());
      }
    }
  });

  $('#searchBtn').on('click', function() {
    that.doSearch($('#searchInput').val());
    return false;
  });
}

function showSearchInput() {
  $('#searchInput').show();
  $('#searchInput').focus();
  $('#searchInput').animate({
    width: 250
  }, 'slow');
}

function hideSearchInput() {
  $('#searchInput').animate({
    width: 0
  }, 'slow'
  , function() {
    $(this).hide();
  });
}

function doSearch() {
...
}

The trick is, don’t hide the search box when the mouse moves away, but rather when the cursor loses focus from the search box. The way to ensure that is to put focus on the search box when it appears. Automatically setting the focus on the search box is also very convenient for your users.

Advertisements