Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom placeholder with contentEditable element

https://jsfiddle.net/cp1ntk45/

I write a function to replace original html placeholder, then I can style the placeholder text.

it works fine with input and textarea element,
problem if the target is contentEditable div, after click once not focus in, not be able to type, need to click second times to focusin ...
How to make only click one time and focus in

var placeholder = function(el) {
  el.on('focusin', function() {
    var val = $(this).text();
    
    var placeholder = $(this).attr('data-placeholder');
    
    if (val == placeholder) {
      if ($(this).attr('data-empty') != 'false') {
        
        $(this).text('');
      }
    }
  });
  el.on('focusout', function() {
    var val = $(this).text();
    var placeholder = $(this).attr('data-placeholder');

    if (val == '') {
      $(this).text(placeholder);

      $(this).attr('data-empty', 'true');
    } else {
      $(this).attr('data-empty', 'false');
    }
  });
};

placeholder($('.textarea'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="textarea" contentEditable="true" data-placeholder="placeholder">placeholder</div>
like image 946
user1575921 Avatar asked Feb 06 '23 18:02

user1575921


1 Answers

You can use CSS :empty and :before on your contenteditable element.
Using the content: attr(data-placeholder) you can than stamp any text you want.

[contenteditable] {padding:12px; background:#eee; }

[data-placeholder]:empty:before{
  content: attr(data-placeholder);
  color: #888;
  font-style: italic;
}
<div contenteditable data-placeholder="I'm a placeholder"></div>
like image 59
Roko C. Buljan Avatar answered Feb 09 '23 09:02

Roko C. Buljan