The Code of No-Code

Apr 17 2013

I had to implement a placeholder for a search box today and discovered, once again, that IE8 & IE9 do not have good support for it. What follows is not a drop in solution, but you should be able to apply the concepts to your particular solution. The first step is to replace the <input/> like so:

<div id="search-container">
  <span id="search-placeholder">{{ searchPlaceholder }}</span>
  <input id="search-query" type="text" name="q" value="{{ searchQuery }}" maxlength="99"/>
  <button type="search-submit">&nbsp;</button>
</div>

You can see to the CSS styling a the end of this post so we can focus on the JS and it's difficulties. First was to find which event (input, keyup, keydown, keypress, or change) worked in both IE8 and IE9. I also experimented with setTimeout and found:

showHidePlaceholder = ->
  setTimeout (->
    value = $.trim $('#search-query').val()
    elm = $('#search-placeholder')
    if value then elm.hide() else elm.show()
  ), 50

showHidePlaceholder()

$('#search-query').on 'keydown', -> showHidePlaceholder()

Because the placeholder is hidden by default we can account for the search-query having a default value, by executing the showHidePlaceholder function immediately after it's defined. This will show the placeholder if there is no value for the search-query, but leave it hidden if the is a value. You can see in the second example below:

NOTE: this code has not been tested in all browsers! It's been adapted from code that was tested, but mistakes made have been made. I hope to test it soon and make an update to this post.

Here is the full CSS from the examples:

#search-container {
  display: inline-block;
  position: relative;
  width: 388px;
  height: 34px;
  margin-right: 13px;
  background: #fff;
}

#search-container span,
#search-container input,
#search-container button {
  position: absolute;
  font-size: 1em;
  font-weight: lighter;
  padding: 0 10px;
  display: inline-block;
}

#search-container span,
#search-container input {
  left: 0;
  height: 32px;
  line-height: 32px;
  width: 350px;
  border: 1px solid #ccc;
  border-right: 0 none;
  background: none;
}

#search-container span {
  color: #bbb;
  display: none;
}

#search-container input {
  color: #666;
}

#search-container button {
  left: 350px;
  border: 0 none;
  height: 34px;
  width: 38px;
  background-color: #00f;
  border: 1px solid #ccc;
  cursor: pointer;
}

#search-container button:hover {
  background-color: #22f;
  border-color: #000;
}