I’m trying to show a toolbar under some selected text once the user has selected some text. I browsed through many stackoverflow answers and the best I could come up with is the code below.
I want the toolbar to trigger when a user selects some text not only on mouse click but also on keyboard selection (alt+shift+arrow keys). Pretty much like in this text editor.
The getSelected()
function returns selected text just fine on either mouse or keyboard selection. But when I go to insert a dummy element at that range, it always inserts (I added some text, "bar", to see where the dummy is inserted) the dummy at the top of the textarea.
I’m guessing it’s got something to do with .getRangeAt(0)
. I want to get the position of the selected text (with the insertion of the dummy <span>
).
function getSelected(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;//.toString()
}
$('#post_content').on('select',function(){
var range = getSelected().getRangeAt(0);
range.collapse(false);
var dummy = document.createElement("span");
// dummy.innerHTML = "bar";
range.insertNode(dummy);
var rect = dummy.getBoundingClientRect();
var x = rect.left, y = rect.top;
dummy.parentNode.removeChild(dummy);
alert(x + "/" + y);
});
Check out the JSFiddle: http://jsfiddle.net/aTq5q/
Any ideas? Thanks!