0

This question is inspired by Insert line break inside placeholder attribute of a textarea?

I didn't find the accepted answer complete-- in part because I don't use JQuery, and in part because if the user enters a string that is exactly equal to the placeholder, the input will be deleted upon refocusing. Also, 
 is not supported by Safari in placeholders.

Any cross-browser non-JQuery solutions to creating a multiline placeholder for a textarea?

Ryan
  • 1
  • 1

1 Answers1

0

Answering my own question -- complete with a dataset attribute to check if the 'value' of the textarea was entered by the user or is from the placeholder.

function addMultilinePlaceholder(textarea, placeholder) {
    // Does textarea have input entered by the user?
    textarea.dataset.hasValue = '';
    textarea.value = placeholder;

    textarea.addEventListener('focus', function () {
        if (!textarea.dataset.hasValue) {
            this.value = '';
        }
    });

    textarea.addEventListener('keyup', function () {
        textarea.dataset.hasValue = (textarea.value.length > 0) ? 'true' : '';
    });

    textarea.addEventListener('blur', function () {
        if (!textarea.dataset.hasValue) {
            this.value = placeholder;
        }
    });
}

Fiddle: https://jsfiddle.net/fm4vyxjL/1/

Ryan
  • 1
  • 1