JavaScript

How to Add Placeholder to a Contenteditable Div Using JavaScript?

The placeholder to a content editable div is provided to offer suggestions and visual cues and to reduce the factor of ambiguity. The placeholder specifically communicates the intended purpose of the “contenteditable” <div> element. The users can see the initial text by the placeholder and understand the text that needs to be entered.

This blog explains the process to insert a placeholder for a Contenteditable Div.

How to Add Placeholder to a Contenteditable Div Using JavaScript?

By placing a placeholder to a Contenteditable HTML div element, the accessibility for end users and additional context and instructions about the purpose of that element gets more prominent. The developer can also apply styling to make the placeholder clearer and to diverge the user’s focus. It can be implemented using both JavaScript and jQuery as stated below examples:

Method 1: Using JavaScript

The JavaScript EventListener’s usage of custom functions plays an important role in placing the placeholder for a contenteditable div. For instance, visit the code:

<style>
  #editable-div {
   border: 1px solid #ccc;
   padding: 10px;
  }
  .placeholder {
   color: gray;
   font-style: italic
  }

</style>
</head>
<body>
  <div id="editable-div" contenteditable="true"></div>
    <script>
      document.addEventListener("DOMContentLoaded", function() {
        var editableDiv = document.getElementById("editable-div");
        var PlaceData = "Enter text here...";

        // Insert placeholder
        function insertPlaceholder() {
          if (editableDiv.textContent.trim().length === 0) {
            editableDiv.innerHTML = '<span class="placeholder">' + PlaceData + '</span>';
          }
        }
        // Hide placeholder
        function hidePlaceholder() {
          if (editableDiv.textContent.trim() === PlaceData) {
            editableDiv.innerHTML = '';
          }
        }
      editableDiv.addEventListener("input", insertPlaceholder);
      editableDiv.addEventListener("focus", hidePlaceholder);
      editableDiv.addEventListener("blur", insertPlaceholder);

      //Check if the div is empty
    insertPlaceholder();
  });

</script>

Explanation of the above code:

  • First, create an editable div and set the value of the “contenteditable” attribute as “true” to make the div “editable”.
  • Next, add the “DOMContentLoaded” event listener that calls an anonymous function, which retrieves and stores the reference of editable div.
  • Also, declare and initialize the variable “PlaceData” with a dummy message that will be set as a placeholder.
  • The “insertPlaceholder” function is defined that includes an “if” statement to check if the length of the “editableDiv” is equal to “0”. Insert the “placeholder” text inside the div by using the “innerHTML” property.
  • Now, create another function to hide or remove the Placeholder with the named “hidePlaceholder”. It utilizes the “if” conditional statement to check if the “editableDiv” content is equal to the “placeholderText”.
  • After that, call the functions “insertPlaceholder()” and “hidePlaceholder()” when the editable div has an event of “input” and “focus” respectively. Also, call or invoke the “insertPlaceholder()” function to check if the “editableDiv” is empty to insert the placeholder.
  • In the end, the custom styling can be done on the “editableDiv” and “placeholder” classes to enhance the visibility factor.

After the compilation, the web page is rendered as:

The output shows that the placeholder on the Contenteditable div has been added.

Method 2: Using jQuery

With the help of jQuery, the same result can be achieved and it makes the process of DOM manipulation and AJAX much easier. It is more efficient and allows developers to easily write code for JavaScript while consuming less time and effort. Below is the demonstration for the creation of a placeholder to a content editable div using jQuery:

<div id="editable-div" contenteditable="true"></div>
  <script>
    $(document).ready(function() {
      var $editableDiv = $("#editable-div");
      var PlaceData = "Insert Date Here";

      // Inserting the placeholder
      function insertPlaceholder() {
        if ($editableDiv.text().trim().length === 0) {
          $editableDiv.html('<span class="placeholder">' + PlaceData + '</span>');
        }
      }
      // Hiding or deleting the placeholder
      function hidePlaceholder() {
        if ($editableDiv.text().trim() === PlaceData) {
          $editableDiv.html('');
        }
      }
      $editableDiv.on("input", insertPlaceholder);
      $editableDiv.on("focus", hidePlaceholder);
      $editableDiv.on("blur", insertPlaceholder);

      insertPlaceholder();
    }
  );
</script>

Explanation for the above code:

  • First, create an editable div by utilizing the “contenteditable” attribute over a “div” element and set its id to “editable-div”.
  • Next, jQuery is utilized to invoke the function after the proper loading of the webpage. Inside the function, the reference to the div is stored in a new variable named “$editableDiv” and the dummy data is inserted in a “PlaceData” variable.
  • Then, a function “insertPlaceholder()” is used that checks the length of the text available in the “div”. If there is no content then the “PlaceData” is inserted in it as a placeholder.
  • After that, define another function “hidePlaceholder()” that checks if there is data in the div then hides the placeholder by inserting empty quotes.
  • In the end, the “insertPlaceholder()” and “hidePlaceholder()” functions are utilized according to the occurrence of the specified event handler to create a dynamic effect.
  • Also, invoke the “insertPlaceholder()” to identify if the “div” element is empty for the placeholder.

After the description:

The output shows that Placeholder has been added on the Contenteditable Div using jQuery.

Conclusion

The placeholder can be added to a Contenteditable div by first creating the <div> and setting its “contenteditable” attribute to “true”. Then, use the “addEventListener()” that calls the functions corresponding to the events like “input”, “focus” or “blur”. The functions check if the div is empty they display the placeholder and if the div contains data or it is in focus, then the placeholder gets hidden. This blog has explained the process to add the placeholder to a Contenteditable div using JavaScript and jQuery.

About the author

Abdul Moeed

I'm a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I'm always eager to help others expand their understanding of technology.