Categories
CSS

How to set the placeholder for contenteditable div with JavaScript?

Spread the love

Sometimes, we want to set the placeholder for contenteditable div with JavaScript.

In this article, we’ll look at how to set the placeholder for contenteditable div with JavaScript.

How to set the placeholder for contenteditable div with JavaScript?

To set the placeholder for contenteditable div with JavaScript, we can set the content CSS style.

For instance, we write

[contenteditable="true"]:empty:not(:focus):before {
  content: attr(data-ph);
  color: grey;
  font-style: italic;
}

to add a placeholder into the contenteditable div with content: attr(data-ph).

This means we use the value of the data-ph as the placeholder content.

We use the [contenteditable="true"]:empty:not(:focus):before pseudo-element to select the contenteditable element and place the content as the first child of it.

This will make the content text show at the start of the element.

Conclusion

To set the placeholder for contenteditable div with JavaScript, we can set the content CSS style.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *