Skip to content

Instantly share code, notes, and snippets.

@kongmunist
Last active September 17, 2023 14:15
Show Gist options
  • Save kongmunist/ae07fc78956486c2121981711a14c4e3 to your computer and use it in GitHub Desktop.
Save kongmunist/ae07fc78956486c2121981711a14c4e3 to your computer and use it in GitHub Desktop.
In-line translator for highlighted words
.highlight-popup {
position: absolute;
background-color: #0044b3;
color: white;
padding: 4px;
border-radius: 4px;
z-index: 9999;
}
translateFrom = "de";
// This detects highlighting and defocus
document.addEventListener('mouseup', function () {
const selectedText = window.getSelection().toString().trim();
if (selectedText !== '' && document.documentElement.lang && document.documentElement.lang === translateFrom) {
console.log('Highlighted word(s):', selectedText);
translate(selectedText).then((res) => {
const range = window.getSelection().getRangeAt(0);
const rect = range.getBoundingClientRect();
const popup = document.createElement('div');
popup.className = 'highlight-popup';
popup.style.top = rect.top - 30 + 'px'; // Adjust the position as needed
popup.style.left = rect.left + 'px';
popup.textContent = res['translatedText'];
document.body.appendChild(popup);
})
}
});
document.addEventListener('mousedown', function () {
const popup = document.querySelector('.highlight-popup');
if (popup) {
popup.remove();
}
})
// Here is my translation function. I'm using a free API that may not exist in the future, but if this is the case then you might be able to find someone else offering a LibreTranslation free endpoint: https://github.com/LibreTranslate/LibreTranslate
async function translate(words){
const res = await fetch("https://translate.terraprint.co/translate", {
method: "POST",
body: JSON.stringify({
q: words,
source: translateFrom,
target: "en",
format: "text"
}),
headers: { "Content-Type": "application/json" }
});
return await res.json();
}
@kongmunist
Copy link
Author

Hello! This is an in-line translator for language learners trying to read their target language. Videos of it running can be found on my Twitter

I'm using a Chrome extension called User Javascript and CSS to run this code - this is because I can't be knackered to make a Chrome extension at the moment. I would love if someone did that though, please tell me if it happens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment