how can we improve the following function to just fetch meanings on rollover not…
- User
how can we improve the following function to just fetch meanings on rollover not selection
// content.js
// Listen for mouseup events (when the user finishes selecting text) document.addEventListener('mouseup', function (e) { let selectedText = window.getSelection().toString().trim();
// Check if the selected text is a single word if (selectedText && !/\s/.test(selectedText)) { // Remove any existing tooltip removeExistingTooltip();
// Fetch meanings of the selected word fetchMeanings(selectedText, e.pageX, e.pageY);} else { // Remove existing tooltip if any removeExistingTooltip(); } });
// Remove tooltip on mousedown (when the user starts a new selection) document.addEventListener('mousedown', function () { removeExistingTooltip(); });
// Function to fetch meanings from the Datamuse API function fetchMeanings(word, x, y) { fetch(
https://api.datamuse.com/words?ml=${word}&max=5) .then(response => response.json()) .then(data => { let meanings = data.map(obj => obj.word); if (meanings.length > 0) { showTooltip(x, y, meanings.join('; ')); } }) .catch(error => { console.error('Error fetching meanings:', error); }); }// Function to display a tooltip near the selected word function showTooltip(x, y, text) { let tooltip = document.createElement('div'); tooltip.id = 'word-meaning-tooltip'; tooltip.innerText = text; // Style the tooltip Object.assign(tooltip.style, { position: 'absolute', top: (y + 10) + 'px', left: (x + 10) + 'px', backgroundColor: '#fffbea', border: '1px solid #ccc', padding: '5px', zIndex: 10000, boxShadow: '2px 2px 6px rgba(0,0,0,0.2)', borderRadius: '4px', fontSize: '14px', color: '#333', maxWidth: '300px', wordWrap: 'break-word' }); document.body.appendChild(tooltip); }
// Function to remove existing tooltip function removeExistingTooltip() { let existingTooltip = document.getElementById('word-meaning-tooltip'); if (existingTooltip) { existingTooltip.remove(); } }
- Assistant