Created
March 30, 2011 13:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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