When a user right-clicks on certain words, the menu opens using JavaScript

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" },
      ]);

});

Answer №1

Start by retrieving the string value of the textarea before launching your personalized context menu. Split the string value of the text area to identify all the words it contains, and then verify if the specific words you are searching for are present.

If the array of words in the string value from the textarea includes any of the specified words, activate your custom context menu. Otherwise, refrain from triggering any action.

let textarea = document.getElementsByTagName("textarea")[0];
let contextMenu = document.getElementsByClassName("custom-context-menu")[0];
specificwords = ['hello', 'hey', 'hi', 'yo', 'some'];

textarea.oncontextmenu = (event) => {
    event.preventDefault();

    let stringValue = event.target.value;
    let words = stringValue.split(' ');
    let result = words.filter(word => specificwords.includes(word))

    if (result.length > 0) {
        let x = event.pageX, y = event.pageY;
        contextMenu.style.left = x + "px";
        contextMenu.style.top = y + "px";
        contextMenu.style.display = "block";

        contextMenu.classList.add("on");
    }
}

document.onclick = (event) => {
    if (contextMenu.classList.contains("on")) {
        contextMenu.classList.remove("on");
        contextMenu.style.display = "none";
    }
}
.custom-context-menu {
    z-index: 1100;
    display: none;
    position: absolute;
    list-style: none;
    margin: 0;
    padding: 0;
    border: 1px solid black;
    background: white;
}

.custom-context-menu li {
    padding: 5px;
    cursor: pointer;
}

.custom-context-menu li:hover {
    background-color: aqua;
}
<!DOCTYPE html>
<head>
    <link href="./main.css" rel="stylesheet"/>
</head>
<body>
    <textarea>hello This is some text. Click on any word and then do right click</textarea>
    <ul class="custom-context-menu">
        <li>rule</li>
        <li>slde</li>
        <li>rebaz</li>
    </ul>
</body>
<script src="./main.js" type="text/javascript"></script> </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

mongoose populate method does not return the expected results

My Project Objective I am currently in the process of creating a travel booking platform for a transportation company. One of the key features I am working on is displaying the name of the individual who made the booking on a specific page within the webs ...

Retrieving information from an array and displaying it dynamically in Next.js

I've been diving into the Next.js framework lately and I've hit a roadblock when it comes to working with dynamic routes and fetching data from an array. Despite following the basics of Next.js, I'm still stuck. What am I looking for? I ne ...

Positioning an image so that it is perfectly aligned on top of another image that is centered

http://jsfiddle.net/Weach/1/ The issue at hand involves a background image created using CSS. This image has been center aligned both horizontally and starting from the top, as visible in the provided JSFiddle link. Specifically, there is another image t ...

Whenever I run my HTML through a server, it doesn't seem to connect with my CSS file

I'm currently developing a Django app, and I have encountered an issue where the CSS is not loading when I run different pages through the server. Oddly enough, everything works fine when I open the files directly without using the server. The problem ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...

What is the maximum character limit for the JQuery validation plugin?

Currently, I am utilizing the JQuery validation plugin in my project. My goal is to set a maxlength for one of the fields. Here's an example of how it can be done by defining rules externally: rules: { Message: { required: false, maxLe ...

Retrieving the length of an array from Firebase Firestore

Recently, I dove into a project that involves using Next JS and Firebase. After successfully storing data in Cloud Firestore, I encountered an issue when trying to retrieve the length of an array from the database. Below is an image illustrating the data s ...

How to handle and display validation errors in an AJAX post request using express-validator in Node.js/Express

I am in the learning phase with Node and attempting to display validation errors (using express-validator and express 4) when a user submits a form. The validator appears to be functioning properly because when I log the data to the console, everything lo ...

The background image is cropped, causing a scroll bar to be added

I've been attempting to add a background image to my HTML using the code below: body { margin: 0; background: url('images/lightning.jpg') no-repeat center center fixed; background-size: cover; -webkit-background-size: cover; -mo ...

SQL Query using Date retrieves Datetime values in a Node application connected to MSSQL

I am currently using version 6.3.1 of node mssql. My query involves multiple columns that are of type date. When querying in node mssql, the output for all Date columns is in this format: 2020-10-20T00:00:00.000Z However, when I execute the same query in A ...

Encourage (or kindly request) the user to refresh the browser

I manage a website that heavily relies on javascript and ajax functionality. I have found ways to make users refresh their browsers upon initial loading, but what about after they have already been using the site? I am looking to improve the speed of the ...

Creating a mesmerizing glass effect in Three.js using a PNG image mask on a video texture

The other day, I revisited activetheory.net and was captivated by the beautiful glass effect on the Homescreen logo border. I tried to replicate it by examining the minified code and discovered they were using a PNG as a mask. I successfully loaded a PNG ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

Issue encountering with flex-wrap to shift to the next row once reaching the 5th element

Recently, I've been experimenting with creating an image gallery using flexbox and incorporating a flex-basis transition to control the growth and shrinkage of elements upon hover. However, I'm encountering difficulties in adjusting the gallery t ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Guide: Displaying components within a Vue2 string

Within my Vue2 component, I am working with a string that looks something like this: <template> <div><h1>Hello World</h1> <div v-html="testString"></div> </div> </template> <script> exp ...

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

Storing information as variables in jQuery

I'm fairly new to working with Javascript and JQuery, and I've encountered a challenge that I initially thought would be straightforward. My project involves creating a website consisting of a single HTML page, a CSS stylesheet, and a JavaScript ...