Skip to content

Instantly share code, notes, and snippets.

@adamgavlak
Created July 15, 2016 20:34
Show Gist options
  • Save adamgavlak/ee4c4bcd75ed5b1554f2c6b3d920947e to your computer and use it in GitHub Desktop.
Save adamgavlak/ee4c4bcd75ed5b1554f2c6b3d920947e to your computer and use it in GitHub Desktop.
document.querySelector(".bold").addEventListener('click', addBold, false);
ta = document.querySelector("textarea[name='content']");
function addBold() {
surroundInTextarea(ta, '**');
return false;
}
function typeInTextarea(el, newText) {
var start = el.selectionStart
var end = el.selectionEnd
var text = el.value
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.value = (before + newText + after)
el.selectionStart = el.selectionEnd = start + newText.length
el.focus()
}
function surroundInTextarea(el, newText) {
var start = el.selectionStart
var end = el.selectionEnd
var text = el.value
var before = text.substring(0, start)
var selection = text.substring(start, end)
var after = text.substring(end, text.length)
el.value = (before + newText + selection + newText + after)
el.selectionStart = start + newText.length
el.selectionEnd = start + newText.length + selection.length
el.focus()
}
<button class="bold">B</button>
<textarea name="content"></textarea>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment