Get Selected Text Position and Place an Element Next to It

Get selected text position and place an element next to it

You could position a marker span at the end of the selection, get its coordinates using jQuery, place your button at those coordinates and remove the marker span.

The following should get you started:

var markSelection = (function() {
var markerTextChar = "\ufeff";
var markerTextCharEntity = "";

var markerEl, markerId = "sel_" + new Date().getTime() + "_" + Math.random().toString().substr(2);

var selectionEl;

return function(win) {
win = win || window;
var doc = win.document;
var sel, range;
// Branch for IE <= 8
if (doc.selection && doc.selection.createRange) {
// Clone the TextRange and collapse
range = doc.selection.createRange().duplicate();
range.collapse(false);

// Create the marker element containing a single invisible character by creating literal HTML and insert it
range.pasteHTML('<span id="' + markerId + '" style="position: relative;">' + markerTextCharEntity + '</span>');
markerEl = doc.getElementById(markerId);
} else if (win.getSelection) {
sel = win.getSelection();
range = sel.getRangeAt(0).cloneRange();
range.collapse(false);

// Create the marker element containing a single invisible character using DOM methods and insert it
markerEl = doc.createElement("span");
markerEl.id = markerId;
markerEl.appendChild( doc.createTextNode(markerTextChar) );
range.insertNode(markerEl);
}

if (markerEl) {
// Lazily create element to be placed next to the selection
if (!selectionEl) {
selectionEl = doc.createElement("div");
selectionEl.style.border = "solid darkblue 1px";
selectionEl.style.backgroundColor = "lightgoldenrodyellow";
selectionEl.innerHTML = "<- selection";
selectionEl.style.position = "absolute";

doc.body.appendChild(selectionEl);
}

// Find markerEl position http://www.quirksmode.org/js/findpos.html
var obj = markerEl;
var left = 0, top = 0;
do {
left += obj.offsetLeft;
top += obj.offsetTop;
} while (obj = obj.offsetParent);

// Move the button into place.
// Substitute your jQuery stuff in here
selectionEl.style.left = left + "px";
selectionEl.style.top = top + "px";

markerEl.parentNode.removeChild(markerEl);
}
};
})();

Getting selected text position

The easiest way is to insert a temporary marker element at the start or end of the selection and get its position. I've demonstrated how to do this before on Stack Overflow: How can I position an element next to user text selection?

JavaScript: Position DIV Centered Above Text Selection?

One solution would be to add the following to your CSS:

.toolbar {
transform: translateX(-50%);
}

and update your script to offset the left position of the toolbar element like so:

$('.toolbar').css({
top: selectionRect.top - 42 + 'px',
left: ( selectionRect.left + (selectionRect.width * 0.5)) + 'px'
});

Here is a working snippet:

$(function() {  // Setup the Event Listener  $('.article').on('mouseup', function() {    // Selection Related Variables    let selection = window.getSelection(),    getRange      = selection.getRangeAt(0),    selectionRect = getRange.getBoundingClientRect();     
// Set the Toolbar Position $('.toolbar').css({ top: selectionRect.top - 42 + 'px', left: ( selectionRect.left + (selectionRect.width * 0.5)) + 'px' }); });});
.article {  position: relative;  height: 300px;  padding: 20px;}
.toolbar { position: absolute; display: flex; align-items: center; justify-content: center; width: 169px; padding-top: 10px; padding-bottom: 10px; background: black; text-align: center; color: white; border-radius: 8px; transform: translateX(-50%);}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script><!-- Editor --><div class="article">  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tenetur dignissimos facilis id repellat sint deserunt voluptates animi eaque tempore debitis, perferendis repudiandae voluptatem. Eligendi fuga deleniti saepe quod eum voluptas.</p></div>
<!-- Toolbar --><div class="toolbar">Toolbar</div>

how do I get co-ordinates of selected text in an html using javascript document.getSelecttion()

Here is the basic idea. You insert dummy element in the beginning of the selection and get the coordinates of that dummy html element. Then you remove it.

var range = window.getSelection().getRangeAt(0);
var dummy = document.createElement("span");
range.insertNode(dummy);
var box = document.getBoxObjectFor(dummy);
var x = box.x, y = box.y;
dummy.parentNode.removeChild(dummy);

How to find index of selected text in getSelection() using javascript?

What you are looking for is available inside object returned by window.getSelection()

document.getElementById('ip').addEventListener('mouseup',function(e){        var txt = this.innerText;        var selection = window.getSelection();        var start = selection.anchorOffset;        var end = selection.focusOffset;        if (start >= 0 && end >= 0){         console.log("start: " + start);         console.log("end: " + end);        }});
<div id="ip">YOLO Cobe</div>

How to get highlighted text position from textarea?

This will work for text selection with the mouse and keyboard for all <textarea> elements on the page.
Change the selector (be more specific) if you don't want all <textarea> elements to have this text selection.

Read the comments, you will find out there how to disable keyboard selection, if you don't want/need keyboard selection.

var mySelection = function (element) {
let startPos = element.selectionStart;
let endPos = element.selectionEnd;
let selectedText = element.value.substring(startPos, endPos);

if(selectedText.length <= 0) {
return; // stop here if selection length is <= 0
}

// log the selection
console.log("startPos: " + startPos, " | endPos: " + endPos );
console.log("selectedText: " + selectedText);

};

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
// register "mouseup" event for the mouse
element.addEventListener('mouseup', function(){
mySelection(element)
});

// register "keyup" event for the keyboard
element.addEventListener('keyup', function( event ) {
// assuming we need CTRL, SHIFT or CMD key to select text
// only listen for those keyup events
if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
mySelection(element)
}
});
});
textarea {
resize: none;
width: 50%;
height: 50px;
margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>


Related Topics



Leave a reply



Submit