How to create editable div using JavaScript?


You will learn in this post how to use HTML, CSS, and JavaScript to develop an editable div. Whenever you click on an editable div, your browser will automatically create an editable text area where you can make changes to or add new text. The text you've edited will appear as a constant text whenever anyone click elsewhere on your browser after you've finished.

Necessary requirements − The concepts of HTML, CSS, and JavaScript should be familiar to you.

Developing structure − Make two files: one for JavaScript and the other for HTML. Execute the command that follows to create these files.

Syntax

$ touch index.html app.js

index.html source code − You have to add the following code in this file as shown below.

<h1 style="color: rgb(12, 139, 185); text-align: center;">
   Let us understand to create Editable Div with TutorialsPoint
</h1>

<div style="text-align: center; margin-left: 35%;" class="container">
   <div id="myFirstDiv"></div>
</div>

CSS source code − You have to add the following code in HTML file as shown below.

body{
   background-color: #b9b9b0;
}
textarea {
   background-color: #e0e1a3;
}

myApp.js source code − The following JavaScript code must be added to the myApp.js file as shown below.

// adding a new element
let divEditing = document.createElement('div');

// text is added to that created element
let value = localStorage.getItem('text');
let text;
if (value == null){
   text = document.createTextNode
   ('You can edit this Div by clicking on it');
}
else{
   text = document.createTextNode(value);
}
divEditing.appendChild(text);
divEditing.setAttribute('id', 'myElem');
divEditing.setAttribute('class', 'myElem');
divEditing.setAttribute('style','font-size:50px;border:2px
solid;width:380px;height:210px;background-color: #80f3e1;');

// the main container is accessible
let container = document.querySelector('.container');

// the element with the ID = myFirstDiv is being inserted
container.insertBefore(divEditing, myFirstDiv);

// event listener is added to the divElem
divEditing.addEventListener('click',function (){
   let lengthOfTextAreas =
      document.getElementsByClassName('textarea').length;
   if(lengthOfTextAreas == 0){
      let html = myElem.innerHTML;
      divEditing.innerHTML =
      `<textarea class="textarea form-control"
      id="textarea" rows="3">
      ${html}</textarea>`;
   }
   
   // listening the textarea's blur event
   let textarea = document.getElementById('textarea');
   textarea.addEventListener('blur',function() {
      myElem.innerHTML = textarea.value;
      localStorage.setItem(
         'text', textarea.value);
   })
});

Example 1

Final Resolution − This is the outcome of combining the HTML, CSS, and JavaScript codes mentioned above.

<!DOCTYPE html>
<html>
<title>How to create editable div using JavaScript - TutorialsPoint</title>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <style>
      body {
         background-color: #b9b9b0;
      }
      textarea {
         background-color: #e0e1a3;
      }
   </style>
</head>
<body>
   <h1 style="color: rgb(12, 139, 185); text-align: center;">
      Let us understand to create Editable Div with TutorialsPoint
   </h1>
   <div style="text-align: center; margin-left: 35%;" class="container">
      <div id="myFirstDiv"></div>
   </div>
</body>
   <script src="myApp.js">
      
      // adding a new element
      let divEditing = document.createElement('div');
      
      // text is added to that created element
      let value = localStorage.getItem('text');
      let text;
      if (value == null) {
         text = document.createTextNode('You can edit this Div by clicking on it');
      } else {
         text = document.createTextNode(value);
      }
      divEditing.appendChild(text);
      divEditing.setAttribute('id', 'myElem');
      divEditing.setAttribute('class', 'myElem');
      divEditing.setAttribute('style', 'font-size:50px;border:2px
         solid; width: 380 px; height: 210 px; background - color: #80f3e1;');
      // the main container is accessible
      let container = document.querySelector('.container');
      
      // the element with the ID = myFirstDiv is being inserted
      container.insertBefore(divEditing, myFirstDiv);
      
      // event listener is added to the divElem
      divEditing.addEventListener('click', function() {
         let lengthOfTextAreas =
            document.getElementsByClassName('textarea').length;
         if (lengthOfTextAreas == 0) {
            let html = myElem.innerHTML;
            divEditing.innerHTML =
               `<textarea class="textarea form-control"
                  id="textarea" rows="3">
                  ${html}</textarea>`;
         }
         // listening the textarea's blur event
         let textarea = document.getElementById('textarea');
         textarea.addEventListener('blur', function() {
            myElem.innerHTML = textarea.value;
            localStorage.setItem(
               'text', textarea.value);
         })
      });
   </script>
</body>
</html>

Output

The above code will give the below output −

You will see this output before clicking the Div area as shown below.


Next, you will see this output after clicking the Div area, enter the text of your choice as shown below.


Finally, you will see this output after entering the text of your choice and hit the cursor (mouse) outside the div element as shown below.


Example 2

Created a <div> with no contentEditable property and a Button element in this case calling the addRemoveAttr() function when the button is clicked.

When performing the function, it checks the value of the contentEditable attribute on the <div id='myText> to see if it is inheritable or false before setting the value of the contentEditable attribute to true.

document.getElementById('txt1').contentEditable = true;

If not, set it to false.

document.getElementById('txt1').contentEditable = false;

To enable or disable the editing functionality on the "div" click the button and you will get the outcome as shown below.

<!DOCTYPE html>
<html>
<title>How to create editable div using JavaScript - TutorialsPoint</title>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   <style>
      #myText {
         background-color: #dfded6;
         width: max-content;
         text-align: center !important;
         border: solid black 2px;
         margin-left: 43%;
      }
   </style>
</head>
<body>
   <body style="text-align:center">
      <h1 style="color: rgb(12, 139, 185); text-align: center;">
         Click the button to enable or disable the Div Element to enter the text.
      </h1>
      <div class='editable' id='myText'>
         <h4>Click Me To Modify the text.</h4>
      </div><br>
      <input button type="button" class="btn btn-success" id='but_enable' value='Click Here' onclick='addRemoveAttr();'>
      <script type='text/javascript'>
         function addRemoveAttr() {
            let contenteditable = document.getElementById('myText').contentEditable;
            if (contenteditable == 'inherit' || contenteditable == 'false') {
               document.getElementById('myText').contentEditable = true;
            } else {
               document.getElementById('myText').contentEditable = false;
            }
         }
      </script>
</html>

You will see this output before clicking the “Click Here” button.

You will see this output after clicking the “Click Here” button and enter the text of your choice.

Updated on: 09-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements