How can I prevent users from selecting text when they right click using JavaScript?

My custom context menu on canvas works well, but I'm facing an issue with Text elements. When I try to right-click on a text element, it triggers text selection as if double-clicking.

I attempted to use the following code:

document.addEventListener('contextmenu', (e) => {
   e.preventDefault();
})

However, this didn't resolve the problem because the text selection still occurs.

https://i.stack.imgur.com/pkZXe.png

Answer №1

Although it may not warrant a full answer, my limited reputation prevents me from leaving a comment. Nevertheless, there are ways to disable certain events like "onCopy", "onCut", "onPaste", and more individually. An example of how to do this can be seen below:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Copy, cut and paste disabled</h2>
    <input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/>
    <br>
  </body>
</html>

If you have any further inquiries, you can refer to the full article here.

Answer №2

One clever technique is using inline JavaScript expressions, such as within form tags.

<form id="test" onsubmit="return false;">

Building off this concept, another example could be seen in:

<canvas oncontextmenu="return false;"></canvas>

In response to feedback: I am not sure about the exact button activation you require, but try experimenting with different numbers like 1, 2, 3, or 4...

document.addEventListener('contextmenu', function(e) {
   // For instance, right-click could correspond to two
    if (e.button == 2) {
      // Preventing default action disables the right-click menu
      e.preventDefault();
    // If e.preventDefault(); does not work, try adding return false;
    }
});

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

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Header and Footer Components in ReactJS

My goal is to design a unique Layout component that will display the Header and Footer. This way, I can later use the Layout like <Layout> ... </Layout> In order to achieve this, I have utilized Routing in both the Header and Footer. To imple ...

What is the best way to structure a hierarchy in an array or object data using Node.js?

I have the following data arrangement: [{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'}, { Country: 'USA', State: 'CA&ap ...

I found myself puzzled by the error message "Module protobufjs not found."

I am currently utilizing the node library known as node-dota2. I have completed all the necessary steps required by node-dota2, as outlined on this site: https://github.com/Arcana/node-dota2#installation-and-setup 1. Installed it using npm 2. Created a fil ...

Tips for utilizing createTextNode in JSDOM

When attempting to create a UI test for an HTML element using Jasmine and jsdom, I encountered an issue. Within my component, I utilized the createTextNode function to populate the content of the DOM element. Unfortunately, during testing, the document.c ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

Discovering the function responsible for styling a DOM elementDiscovering how to identify the

I have a Prestashop 1.6 store and I've noticed that when I scroll down, my main menu becomes fixed at the top of the page. However, when I scroll back up, it reverts to its default position in the header. The issue is that the height of the menu is se ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

When Highcharts and AngularJS team up, beware of the memory leak!

I've integrated highcharts into my AngularJS application using the highcharts-ng directive, but I'm encountering a persistent memory leak issue. My app is a slideshow with rotating slides that include charts. To investigate further, I created 3 ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

execute a retrieval query on an html pop-up

I have recently created an HTML web resource that I am displaying when a ribbon button is clicked. Within this popup, there is a dropdown list that I intend to fill with records obtained through a fetchXml query. The issue I'm encountering is that de ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Turn off and then turn on user input without exiting the textarea

I've been working on a small project that requires me to enable and disable text input in a textarea using key commands, similar to Vi/Vim's insertion and command modes. However, I'm struggling to find an elegant solution. Disabling the tex ...

Storing an ID field across different domains using HTML and JavaScript: Best Practices

Currently, my web app includes a conversion tracking feature that analyzes whether activity "A" by a website visitor leads to action "B." This feature works effectively when the tracking is contained within a single domain but encounters issues across mul ...

The localhost successfully accessed req.session.userid, but unfortunately the virtual host cannot be reached at this time

Having some trouble here... I've spent days trying to figure it out but nothing seems to be working. I am using Node.js Express session on the backend with users. When I log in, I set req.session.userId = "userid" and have a middleware that ...

Creating interactive comments in Vue 3 using dynamic rendering

Is there a way to properly display a dynamic comment in Vue 3? I attempted using v-html, but it's not working as expected in my scenario. Here is the example: <template> <!-- Method 1: not displaying correctly, https://i.sstatic.net/ddX39. ...

The 'xxx' type is lacking various properties compared to the 'xxx[]' type, such as length, pop, push, concat, and many others

Utilizing typescript and reactjs, the issue lies within this component import type { InputProps } from "../utils/types" const Input = (props: InputProps) => { const makeChildren = () => { return ( <> ...

Trigger a 'change password' notification using Javascript

Issue: I am currently working on developing a web application that includes a password change functionality without the use of form submission. The process I have in mind is as follows: Show a Bootstrap modal pop-up User enters new password Upon clickin ...