Skip to content

Instantly share code, notes, and snippets.

@oslego
Created March 30, 2011 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oslego/894390 to your computer and use it in GitHub Desktop.
Save oslego/894390 to your computer and use it in GitHub Desktop.
Convert a plain text field into a search field with focus/blur behavior
/**
Turn a text input into a search input with added behavior
On focus, if input value is the same as defaultValue, replace with blank
On blur, if input value is empty or full of whitespace replace with defaultValue
@param input {HTMLInputElement} element to behave as search input
@param defaultValue {String} string to be default value of the input
**/
function makeSearchInput(input, defaultValue){
input.setAttribute("data-default", defaultValue);
input.setAttribute("value", input.getAttribute("data-default"))
input.addEventListener("focus", function(e){
if (input.value == input.getAttribute("data-default"))
input.value = "";
}, false);
input.addEventListener("blur", function(e){
if (!input.value.length || !q.value.replace(/\s/,"").length)
input.value = input.getAttribute("data-default")
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment