Search code examples
javascripthtmltextareaplaceholder

How do I add a default text to the beginning of an html text area?


Im building a personal little social network. As part of the design, all statuses should begin with a default text that shouldn't change, similar to "Hi, my name is…" and then the user finishes the rest. Kind of like an HTML5 placeholder that doesn't go away. What would be the best way to accomplish this?


Solution

  • Note: For some dumb reason, I assumed jQuery (note that you do not need jQuery for this, but makes it a little easier).

    Here is one solution uses a combination of text-indent and an absolutely positioned <span> (for the prefix part).

    Demo: http://jsfiddle.net/4YzZy/


    $('textarea.withprefix').each(function() {
      var prefix = $('<span/>')
                  .text($(this).data('prefix'))
                  .addClass('prefix')
                  .appendTo('body')
                  .css({
                      left: $(this).position().left + 'px',
                      top: $(this).position().top + 'px',
                  });
      $(this).css({textIndent: prefix.outerWidth() + 'px'});
    });
    textarea, span.prefix {
        font-family: arial; /* change these as needed, but ensure that the textarea and the span use the same font */
        font-size: 1em;
        font-weight: normal;
        padding: 2px;
        border-width: 1px;
    }
    span.prefix {
        position:absolute;   
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea class="withprefix" data-prefix="Hi There, "></textarea>