0

I have a div with contenteditable enabled. When pressed enter, it inserts br or when everything is emptied (by deleting the contents inside), it also inserts br.

Is there a way to control what gets inserted in either cases? For example, I want to insert a div when pressed enter. Furthermore I want to include a div (which acts more like placeholder) when I delete everything inside.

For the second part (ie: div that acts like placeholder), I know I can use css such as below:

div.example[contenteditable]:empty::before {
  content: "Acts like a placeholder";
}

But it seems that when I delete everything inside, br is inserted and I can't get rid of it.

Hope I am being clear. Anyway, any help will be much appreciated.

Thank you.

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • can you add your markup and js code where your are handling the insertion and deletion code – Geeky Dec 01 '16 at 01:15

1 Answers1

1

You can handle Enter key event and include div on insertion or deletion by checking the content length

check the following snippet

$(document).ready(function() {

});

jQuery('#editDiv').on("keypress", function(e) {

  if (e.keyCode == 13) {
    $(this).append("<div>new div</div>")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="editDiv">
  hello
</div>

you can check this link too Jquery Event : Detect changes to the html/text of a div

Hope it helps

Community
  • 1
  • 1
Geeky
  • 7,420
  • 2
  • 24
  • 50