Last active
October 15, 2019 19:48
-
-
Save topin89/dd8d47984011fb3954abd5a86b11b35e to your computer and use it in GitHub Desktop.
Marking text in textarea with b and i tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Notabenoid bbcode shortkey | |
// @namespace http://notabenoid.zapto.org/ | |
// @version 0.1 | |
// @description enter something useful | |
// @match http://notabenoid.zapto.org/* | |
// @copyright 2019, topin89@mail.ru | |
// ==/UserScript== | |
function changeSel(chr) // javascript | |
{ | |
// obtain the object reference for the <textarea> | |
var txtarea = document.activeElement; | |
var isInputText = txtarea instanceof HTMLTextAreaElement; | |
if(!isInputText) {return ;} | |
// obtain the index of the first selected character | |
var start = txtarea.selectionStart; | |
// obtain the index of the last selected character | |
var finish = txtarea.selectionEnd; | |
var str = txtarea.value | |
var opentag = '<'+chr+'>' | |
var closetag = '</'+chr+'>' | |
var new_str = '' | |
if(str.includes(opentag) && str.includes(closetag)){ | |
new_str =str.replace(opentag, '').replace(closetag, '') | |
}else{ | |
new_str =str.substring(0,start) + opentag + str.substring(start,finish) + closetag + str.substring(finish); | |
} | |
txtarea.value = new_str; | |
txtarea.setSelectionRange(start, finish + new_str.length - str.length); | |
} | |
function doc_keyDown(e) { | |
if(e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey){ | |
if(e.code == "KeyB"){ | |
changeSel('b'); | |
e.stopImmediatePropagation(); | |
e.preventDefault(); | |
}else if(e.code == "KeyI"){ | |
changeSel('i'); | |
e.stopImmediatePropagation(); | |
e.preventDefault(); | |
} | |
} | |
} | |
document.addEventListener('keydown', doc_keyDown, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment