Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theraaz/5e900c084ebac454162e to your computer and use it in GitHub Desktop.
Save theraaz/5e900c084ebac454162e to your computer and use it in GitHub Desktop.
Textarea Placeholder with Newlines
textarea.placeholder {
color: #aaa;
}
<textarea placeholder="key,val \n key,val \n key,val"></textarea>
/**
* Allows the use of placeholder text that includes new lines in textareas.
*
* @author: Ben Dechrai <[email protected]>
* @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').replace(/\\n/g,'\n') ) {
$(this).val('');
$(this).removeClass('placeholder');
}
});
// On blur, if value = blank, insert placeholder
$(this).blur(function(e){
if( $(this).val() == '' ) {
$(this).val($(this).attr('data-placeholder').replace(/\\n/g, '\n'));
$(this).addClass('placeholder');
}
});
// Call blur method to preset element - this will insert the placeholder
// if the value hasn't been prepopulated
$(this).blur();
});
}
@theraaz
Copy link
Author

theraaz commented Mar 26, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment