Friday 16 May 2014

Customize the SmallSearchInputBox

Sometimes you need to customize the OTB searchbox but without touching control templates or building out your own custom webpart control. This restriction commonly comes from environments in which you are restricted to just SharePoint Designer. To resolve this I would utilize JavaScript and CSS to just customize the look and feel of the SearchBox. the following is a native JS implementation to change the placeholder text and to rewire the the onblur event to use a new function that would reset the placeholder text to what we specified.

var spm= spm|| {};

if (typeof spm.searchBoxExtension == 'undefined' || spm.searchBoxExtension == null)
{
  spm.searchBoxExtension = {

    init: function() {

      var searchBox = document.getElementsByName("InputKeywords")[0];
      searchBox.value = "What are you searching for?";
      searchBox.onblur = this.customBlur;
    },

    customBlur: function(event) {
      if (this.value == '') {
        this.value = 'What are you searching for?';

        if (this.className.indexOf('s4-searchbox-QueryPrompt') == -1)
          this.className += this.className ? ' s4-searchbox-QueryPrompt' : 's4-searchbox-QueryPrompt';

        document.getElementById('ctl00_PlaceHolderSearchArea_ctl01_ctl04').value = '0'
      } else {
        document.getElementById('ctl00_PlaceHolderSearchArea_ctl01_ctl04').value = '1';

      }
    }
  }
}

(function(){
  _spBodyOnLoadFunctionNames.push("spm.searchBoxExtension.init");
})()