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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: