Steve Kim
Steve Kim

Reputation: 5591

Contenteditable: Add div instead of br

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.

Upvotes: 0

Views: 328

Answers (1)

Geeky
Geeky

Reputation: 7498

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

Upvotes: 1

Related Questions