I'm trying to get the cursor position inside a textarea in order to handle a custom wysiwig editor I'm building.
It's working correctly except for one thing. When no text is selected, right now I'm adding the BBCODE at the end of the current input. I would rather like to insert that BBCODE in the current cursor position.
This is what I have right now
function loadEditor(){
var input = document.getElementById('editor-content');
var btnBold = document.getElementById('bold');
var blur = null;
var clearSelect = function() {
input.setSelectionRange(0, 0);
};
input.addEventListener('blur', function() {
blur = setTimeout(clearSelect, 0);
});
btnBold.addEventListener('focus', function() {
if (blur !== null) {
clearTimeout(blur);
blur = null;
}
});
btnBold.addEventListener('click', function() {
var openCode = "[b]";
var closeCode = "[/b]";
var emptyValue = openCode + closeCode;
var fullText = input.value;
var selected = input.value.substring(input.selectionStart, input.selectionEnd);
if(selected == ""){
input.value = input.value + emptyValue
}else{
input.value = input.value.replace(selected,openCode+selected+closeCode);
}
clearSelect();
});
}
Thanks for your assistance