JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>
<h2>Modified behaviors</h2>
<!-- To get simulated placeholder with New Lines behavior,
add the data-placeholder attribute -->
<textarea data-placeholder> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address' data-placeholder> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<h2>Standard behaviors</h2>
<textarea placeholder='Address'> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address'></textarea>
CSS
textarea{
width:300px;
height:80px;
color:DarkGreen;
}
textarea.placeholder {
color:gray;
}
h1 {
display: block;
font-size: 1.5em;
-webkit-margin-before: 0.83em;
-webkit-margin-after: 0.83em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
font-weight: bold;
}
h2 {
display: block;
font-size: 1.17em;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
font-weight: bold;
}
JavaScript
handleFocus = function(){
var $this = $(this);
if($this.val() === $this.attr('data-placeholder')){
$this.val('');
$this.removeClass('placeholder');
}
};
handleBlur = function(){
var $this = $(this);
if($this.val() == ''){
$this.val($this.attr('data-placeholder'))
$this.addClass('placeholder');
}
};
$('textarea[data-placeholder]').each(function(){
var $this = $(this),
value = $this.val(),
placeholder = $this.attr('placeholder');
$this.attr('data-placeholder', value ? value : placeholder);
$this.val('');
$this.focus(handleFocus).blur(handleBlur).trigger('blur');
});