1

This is my current code. I'm hoping to make a tiny cross browser markdown editor for only a few tiny controls. This is what I have so far:

http://jsfiddle.net/spadez/c3hHC/3/

What I want to do is get my current selection in jquery (if anything in the text box is selected) and if bold is clicked, both prepend and append the selected text with this:

**

It seems like to encase the selected text in two stars either side when the bold button is clicked I need to do the following:

Listen for a click: .click(function()
append: .append()
prepend: .prepend()

Can anyone help me get the current selection using jquery so I can add the stars to either side please?

J.Zil
  • 2,397
  • 7
  • 44
  • 78

1 Answers1

1

You could use my jQuery plug-in for this.

Demo: http://jsfiddle.net/timdown/bAxee/5/

Code:

$('#description').surroundSelectedText("**", "**");

If you don't need to support IE <= 8, the following answer will do the job without need of a jQuery plug-in:

How do I use JavaScript to change the position of a cursor and then place new content at it?

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I'm creating a markdown-editor for my website. Also I use [this](https://github.com/jgm/commonmark.js) to show the output to clientside. Now I have some icon in the top of that textarea (for e.g. `B`, *`I`*). Well, I need something similar with what you have linked in this answer (but for all icons (code-method, quote, link, ..), not just for `bold`). Is there any suggestion? – Shafizadeh Jan 16 '16 at 16:03
  • That plugin just selects selected-text. And then I can add something around it like two stars .. But actually I need to check whether is there two stars around the selected text? if yes, remove them, else add two stars ...! Something exactly like SO. Is there any API for that? – Shafizadeh Jan 16 '16 at 16:26
  • Thanks Tim. That's exactly what I needed, perfect ..! Just one point, How can I use `.trim()` to your library for selected text ? *(which part of it)* thanks again – Shafizadeh Jan 18 '16 at 22:34
  • And if using `.trim()` is impossible, I also have a regex which handles spaces as well `$textarea.val( $textarea.val().replace(/\s*(\*+)\s*(.*?)\s*(\*+)\s*/g,' $1$2$3 ') );` and it should be add on line 13 *(of your fiddle)*, But when I add it, text-highlighting hides when I click on *Bold*, Well, can you please give me a solution? – Shafizadeh Jan 19 '16 at 01:54