Prevent selection, enable copying and pasting

As I develop an application that alters the default selection behavior to allow the copying and pasting of elements, a challenge has arisen. Disabling the ability to select also eliminates copy events.

I initially attempted to use the following:

onselectstart="return false;"

and

.no-select {     
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;  
}

While these methods successfully disabled selecting, they also hindered copying.

Subsequently, I experimented with applying the .no-select attribute solely to text-containing sections, but this approach proved challenging to maintain and inconsistent in functionality – leading to unpredictable blocking of copy events.

My inquiry is this - How can I effectively disable selection while enabling proper copy/paste mechanisms?


Edit:

  • I am not looking to copy text, but instead my own JSON structures. Copying is managed within the onCopy handler.
  • I must be able to intercept standard Chrome copy events triggered by the Chrome menu or system shortcuts.

Answer №1

If you disable highlighting/selecting, what do you want to copy? Unselected items remain unchanged

I prefer not to copy text (as is the standard behavior), but rather my own JSON representation of objects

I have two solutions for your issue:

  1. Replace the context menu with a function that copies to the clipboard (tutorial and library)

    if (document.addEventListener) {
            document.addEventListener('contextmenu', function(e) {
                alert("Create custom menu for copying");
                e.preventDefault();
            }, false);
        } else {
            document.attachEvent('oncontextmenu', function() {
                alert("Create custom menu for copying");
                window.event.returnValue = false;
            });
        }
    body {     
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;  
    }
    <body>
    Some text
    </body>

  2. Add a "Copy" button with a function that copies to the clipboard (tutorial and library)

  3. Assign the key combination ctrl + c (or other combinations like command + c) to a function that copies to the clipboard (tutorial and library)
  4. Consider using Flash or another external browser addon for copying to the clipboard (not recommended)

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

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

How to access a file stored within a proxy object using Vue.js

I am currently working on sending a file from a vue-page to the server. To achieve this, I have implemented the following: FileFrom component: <template> <div class="FileForm" v-bind:name="name"> <label clas ...

What steps can be taken to resolve a Mediasoup installation error in a Node.js environment?

While attempting to install the mediasoup library, I ran into an error that has me stumped. If anyone has encountered this issue before or knows how to solve it, any assistance would be greatly appreciated. > <a href="/cdn-cgi/l/email-protection" c ...

The PointCloud vertices in Three.js consistently provide a position of (0,0,0)

I'm working with a PointCloud named "cloud" that is centered at (0, 0, 0) and consists of approximately 1000 vertices. These vertices' positions are being manipulated by a vertex shader. My goal now is to log the position of each vertex to the co ...

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

Struggling to resolve a common issue in Migration? It seems that a raw query in Sequelize is adding backslashes that are causing errors when inserting values into the database

During migration, data is taken from one table and inserted into another. However, an issue arises when Sequelize adds backslash escape characters to the 'v_occupation' value, causing insertion errors. I have attempted various replacements and m ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Why am I receiving the error message 'Uncaught TypeError: results is not a function' while utilizing the map function?

Struggling to grasp the concept of the map function and puzzled by why my output is showing [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined], even though I've provided the correct this value as per the documenta ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Learn how to easily navigate to your profile page by clicking on a button after logging into your account

I created a homepage with a button for users to either login or go to their profile. My intention is for the button to function as follows: When a user logs in, the button will display the username and clicking on it will take the user to their profile pa ...

Guide to using AES-256-CBC encryption in Node.js and decrypting with OpenSSL on a Linux system

Question: Hello there, I am currently facing an issue with decrypting my encoded base64 using a specific command. Here is the command that I am trying to use: echo "base64key" | (openssl enc -AES-256-cbc -d -a -pass "pass:test" -pbkdf2 ...

Send JSON information to the server and interpret the feedback with JavaScript

Can someone please provide guidance on how to send JSON format data via POST to a server URL, receive the response in JSON format, parse it, and retrieve the data? An example would be greatly appreciated. Thank you. ...

Is it feasible in JavaScript to restrict selecting only complete nodes within a range selection?

Is it possible to prevent the selection of a partial node in JavaScript range selection? For instance: "The massive dog ran across the street." When a user selects "dog", their selection may inadvertently include neighboring words li ...

Redux - a method of updating state through actions

Hello, I am currently working on developing a lottery system and I have a question regarding the best approach to modify state using action payloads. Let's consider the initial state: type initialCartState = { productsFromPreviousSession: Product[ ...

Troubleshooting Problem with Centering Rows in Bootstrap

I am utilizing the most recent version of Bootstrap 3 to design a website for a friend, but I am encountering a challenge with centering elements on the page. Typically, I would use the following code: .center{ width: 90%; margin: 0 auto; } Howev ...

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Having trouble getting the full width of a hidden div to work properly?

I am facing an issue with a two-part menu design: the left side consists of a traditional UL, while the right side contains a link within a div element. The fixed-width of the right div is causing complications as the left div needs to occupy all remaining ...

Is there a way to extract the code from the "View Page Source" option on a website using BeautifulSoup or a different library?

While perusing the website, we are given the choice to "View source" and "View page source". BS4 allows us to extract data from the "View page source", but is it feasible to extract data from the "View source"? If not, what alternative methods can be use ...