I am trying to position a <div>
above a users text selection that will act as a toolbar similar to Mediums.
While I have successfully gotten the <div>
to be positioned next to the selection, I cannot seem to get it to correctly center relative to the selection:
$(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 + 'px'
});
});
});
I can determine the selection's center point by subtracting the selections left offset from the viewport by its width as such:
selectionRect.left - selectionRect.width
However, I am not sure how to use that to set the position of my toolbar to be centered relative to the selection rectangle?
I tried subtracting the toolbars left offset from the width of the selection divided by 2 but that doesn't align to the center perfectly either.
JSFiddle