<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Text Selection Toolbar for Textarea (Accurate Positioning)</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-4">
<div class="max-w-screen-2xl mx-auto relative">
<textarea contenteditable="true" id="myTextarea" class="w-full h-96 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Select some text...">
This demo leads me to realise that it may be easier to set contenteditable=true on a more compatible element... but why is textarea not playing ball?
I guess this is what I get for not paying too much attention to advanced HTML and this whacky CSS stuff... perhaps in another life!
...by the way, when selecting text - if we mouse up OUTSIDE of the textare the popup doesn't show! ..also this is a very rudimentary demo, sorry!
- If the main viewport is too small the offset isn't calculated correctly. Sorry not sorry.
</textarea>
<div id="mirrorDiv"></div>
<!-- Custom toolbar -->
<div id="customToolbar" class="hidden fixed bg-white shadow-md rounded-md p-2 flex space-x-2 z-50">
<button class="bg-blue-500 text-white px-3 py-1 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">B</button>
<button class="bg-green-500 text-white px-3 py-1 rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500">I</button>
<button class="bg-red-500 text-white px-3 py-1 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500">U</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.getElementById('myTextarea');
const mirrorDiv = document.getElementById('mirrorDiv');
...