Skip to content

Instantly share code, notes, and snippets.

@bendechrai
Last active March 26, 2016 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bendechrai/545e70d4555fe8d029fd to your computer and use it in GitHub Desktop.
Save bendechrai/545e70d4555fe8d029fd to your computer and use it in GitHub Desktop.
Textarea Placeholder with Newlines
textarea.placeholder {
color: #aaa;
}
<textarea placeholder="key,val
key,val
key,val"></textarea>
/**
* Allows the use of placeholder text that includes new lines in textareas.
*
* @author: Ben Dechrai <ben@dechrai.com>
* @readme: https://bendechrai.com/2013/04/03/textarea-placeholder-with-new-lines/
* @licence: http://opensource.org/licenses/MIT
*/
function textareaPlaceholderNewlines() {
$('textarea[placeholder*="\n"]').each(function(){
// Store placeholder elsewhere and blank it
$(this).attr('data-placeholder', $(this).attr('placeholder'));
$(this).attr('placeholder', '');
// On focus, if value = placeholder, blank it
$(this).focus(function(e){
if( $(this).val() == $(this).attr('data-placeholder') ) {
$(this).attr('value', '');
$(this).removeClass('placeholder');
}
});
// On blur, if value = blank, insert placeholder
$(this).blur(function(e){
if( $(this).val() == '' ) {
$(this).attr('value', $(this).attr('data-placeholder'));
$(this).addClass('placeholder');
}
});
// Call blur method to preset element - this will insert the placeholder
// if the value hasn't been prepopulated
$(this).blur();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment