user1854458
user1854458

Reputation: 665

How to Wrap Text in a Content Editable Div Per Line

I would like to understand if I can wrap text in a content editable div.

For example, if a user uses markup to type

### MY TITLE

can I somehow parse that line and create another div that outputs

<b>MY TITLE<b>

I've created a jsfiddle to observe the output, but I don't see much that tells me where a line ENDS to put the closing tag. In addition, the output looks pretty weird after hitting the return key a couple times. It seems difficult to work with and I was hoping there be better indicators of what the user had typed.

"
        ### test 
        &lt;div&gt;&lt;br&gt;&lt;/div&gt;"

https://jsfiddle.net/rn2camL4/1/

Upvotes: 0

Views: 159

Answers (1)

Aib Syed
Aib Syed

Reputation: 3196

If I'm understanding correctly, you just want to put bold tags around the output, if so, you can accomplish this with a simple concatenation.

I brought your jsfiddle over into the snippet below, please run it to see it in action.

When you console.log(boldHtml) you will see the output wrapped in <b></b>.

$('#editable').on('keydown', function(e) {
  let html = $(this).html();
  //concatenate bold tags around your html and declare new boldHtml variable
  let boldHtml = '<b>' + html + '</b>'
  $('#render').html(boldHtml) // replace test with <b>test</b>
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editable" contenteditable="true" style="background-color:white; outline: 0px solid transparent; width: 100%; padding: 16px;">
  ### test
</div>

<div id='render'>

</div>

Alternatively, if you're fine with using a library, you can use markdown-it for example and have it convert any type of markdown into HTML.

I've applied the logic to your code below.

When you console.log(markdown) you will see the correct HTML tags around your output.

const md = window.markdownit();


$('#editable').on('keydown', function(e) {
  let html = $(this).html();
  let markdown = md.render(html);
  $('#render').html(markdown) // replace any markdown with proper html

  //console.log(markdown);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/markdown-it.min.js"></script>

<div id="editable" contenteditable="true" style="background-color:white; outline: 0px solid transparent; width: 100%; padding: 16px;">
  Enter ANY markdown here
</div>

<div id='render'>

</div>

Upvotes: 1

Related Questions