Forked from bendechrai/textareaPlaceholderNewlines.css
Last active
March 26, 2016 21:49
-
-
Save theraaz/5e900c084ebac454162e to your computer and use it in GitHub Desktop.
Textarea Placeholder with Newlines
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
textarea.placeholder { | |
color: #aaa; | |
} |
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
<textarea placeholder="key,val \n key,val \n key,val"></textarea> |
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
/** | |
* 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(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
demo at https://jsfiddle.net/theraaaz/1t67ap3x/1/