Looking to implement a custom context menu that opens when specific words are right-clicked by the user in JavaScript. I have been searching for a solution for quite some time now. The word should be recognized based on an array of specific words. Can someone assist me with this? This is just an example of how the context menu should work, not specifically within a textarea like the one found here https://codepen.io/rebaz-xoshnaw-the-builder/pen/XWOPvRe. If the word in the textarea does not match any of the specificwords in the array, the context menu should not open. It's important to note that the provided code snippet is just a suggestion and is unrelated to the original source.
var specificwords = ['hi', 'hello', 'yo', 'hey', 'some', 'howdy'];
document.querySelector('textarea').addEventListener('contextmenu', function (e) {
e.preventDefault();
var startPosition = this.selectionStart,
endPosition = this.selectionEnd;
while (this.value.charAt(startPosition) !== ' ' && startPosition >= 0) {
startPosition--;
}
while (this.value.charAt(endPosition) !== ' ' && endPosition < this.value.length) {
endPosition++;
}
this.selectionStart = startPosition + 1;
this.selectionEnd = endPosition;
})
<textarea>hello This is some text. Click on any word and then do a right-click</textarea>
document.getElementById("my-message").addEventListener("contextmenu", (e) => {
// Prevent the usual context menu from appearing
e.preventDefault();
// Show our custom context menu instead
window.todesktop.contextMenu.create([
{
label: "Add Emoji",
click: () => {
// In this case, you would provide the `showEmojiPanel` function
showEmojiPanel();
},
},
{ type: "separator" },
{ role: "copy" },
{ role: "paste" },
]);
});