Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I actually figured this one out myself... I used the Rangy library <a href="https://code.google.com/p/rangy/" rel="nofollow">https://code.google.com/p/rangy/</a> and code like this:</p> <pre><code> // Add text to the reply area at the very end, and move the cursor to the very end. function insertText(textarea, text) { textarea = $(textarea); textarea.focus(); textarea.val(textarea.val() + text); textarea.focus(); // Trigger the textarea's keyup to emulate typing. textarea.trigger("keyup"); } // Add text to the reply area, with the options of wrapping it around a selection and selecting a part of it when it's inserted. function wrapText(textarea, tagStart, tagEnd, selectArgument, defaultArgumentValue) { textarea = $(textarea); // Save the scroll position of the textarea. var scrollTop = textarea.scrollTop(); // Work out what text is currently selected. var selectionInfo = textarea.getSelection(); if (textarea.val().substring(selectionInfo.start, selectionInfo.start + 1).match(/ /)) selectionInfo.start++; if (textarea.val().substring(selectionInfo.end - 1, selectionInfo.end).match(/ /)) selectionInfo.end--; var selection = textarea.val().substring(selectionInfo.start, selectionInfo.end); // Work out the text to insert over the selection. selection = selection ? selection : (defaultArgumentValue ? defaultArgumentValue : ""); var text = tagStart + selection + (typeof tagEnd != "undefined" ? tagEnd : tagStart); // Replace the textarea's value. textarea.val(textarea.val().substr(0, selectionInfo.start) + text + textarea.val().substr(selectionInfo.end)); // Scroll back down and refocus on the textarea. textarea.focus(); // If a selectArgument was passed, work out where it is and select it. Otherwise, select the text that was selected // before this function was called. if (selectArgument) { var newStart = selectionInfo.start + tagStart.indexOf(selectArgument); var newEnd = newStart + selectArgument.length; } else { var newStart = selectionInfo.start + tagStart.length; var newEnd = newStart + selection.length; } textarea.selectRange(newStart, newEnd); // Trigger the textarea's keyup to emulate typing. textarea.trigger("keyup"); } var bbcode = { bold: function(id) {wrapText($("textarea"), "[b]", "[/b]", "", "bolded text");}, }; </code></pre> <p>Example usage:</p> <pre><code>bbcode.bold(); </code></pre> <p>Full code (in a larger project I did): <a href="https://github.com/wnajar/textarea" rel="nofollow">https://github.com/wnajar/textarea</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload