This project enables inline text translation on any webpage by allowing users to click on a text element and select a target language from a modal popup. The tool is lightweight, user-friendly, and easily integrable into any project.
- Click-to-edit: Click on any
.text-editorelement to open the editor. - Multi-language support: Choose from 40+ languages.
- Auto-translation: Works with your own translation API (default uses
localhost:8000/translate). - Modular design: Easily integrable into any modern project.
- Tag-safe editing: HTML tags are highlighted and locked (non-editable).
- Create a New Project
npx roy404-text-editor project-name- Install dependencies
npm install
npm install node-fetch- Start the Development Server
npm run serveThis will launch a local server to serve your index.html.
Make sure your local server handles requests to:
GET http://localhost:8000/translate?q=Hello&to=esResponse format:
{ "translation": "Hola" }In your main.js:
import compileTextEditors from './text-editor/text-editor.js';
// Basic usage with default translation logic
compileTextEditors('.text-editor');compileTextEditors('.text-editor', ({ element, lang, translation }) => {
console.log(`[${lang}] saved for element:`, element);
console.log('Translated content:', translation);
});You can override the default mockTranslate() by supplying your own async translation function:
const customTranslate = async (text, lang) => {
const res = await fetch(`/api/translate?q=${encodeURIComponent(text)}&to=${lang}`);
const json = await res.json();
return json.translation;
};
compileTextEditors('.text-editor', null, customTranslate);To safely initialize the editor only after the DOM is loaded:
import compileTextEditors from './text-editor/text-editor.js';
document.addEventListener('DOMContentLoaded', () => {
compileTextEditors('.text-editor', ({ element, editorId, lang, translation }) => {
console.log(`Saved [${lang}] for element #${editorId || '(no ID)'}`);
console.log('Translated text:', translation);
}, async (text, lang) => {
// Example custom translation handler
const res = await fetch(`/translate?q=${encodeURIComponent(text)}&to=${lang}`);
const json = await res.json();
return json.translation;
});
});This pattern ensures all .text-editor elements are present before the translator attaches listeners.
compileTextEditors(
selector: string, // Required: CSS selector for clickable text
onSave?: ({
element, // HTMLElement - The clicked DOM element
lang, // string - Language code selected (e.g., 'en', 'fr')
translation // string - Translated text content
editorId, // string - The value of the `data-editorid` attribute (if present)
}) => void,
customTranslateFn?: async (text: string, lang: string) => Promise<string> // Optional: Your own translation function
)
