Created
April 5, 2013 14:22
-
-
Save catchamonkey/5319645 to your computer and use it in GitHub Desktop.
JavaScript placeholder polyfill.
This file contains hidden or 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
function isPlaceholderSupported() { | |
var input = document.createElement("input"); | |
return ('placeholder' in input); | |
} | |
var placeholdersupport = isPlaceholderSupported(); | |
// find the elements that are advertising this behaviour | |
// then setup each one | |
$("[data-behaviour='placeholder']").each(function() { | |
var placeholderText, elements, inputValue; | |
element = $(this); | |
placeholderText = element.attr('placeholder'); | |
inputValue = element.attr('value'); | |
// use the input value if present instead of the placeholder | |
if (inputValue != '') { | |
placeholderText = inputValue; | |
}; | |
// polyfill | |
if (!placeholdersupport) { | |
element.val(placeholderText); | |
element.focus(function() { | |
if ($(this).val() == placeholderText) { | |
$(this).val(''); | |
} | |
}); | |
element.blur(function() { | |
if($(this).val() == '') { | |
$(this).val(placeholderText); | |
} | |
}); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment