javascript code to use mouse button to copy text on webpage

You can use JavaScript to implement a custom copy function that is triggered when the user clicks a mouse button. Here is an example code that copies the selected text to the clipboard when the user right-clicks on it:

document.addEventListener('contextmenu', event => {
  event.preventDefault();
  const selection = window.getSelection().toString();
  if (selection) {
    copyToClipboard(selection);
  }
});

function copyToClipboard(text) {
  const el = document.createElement('textarea');
  el.value = text;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

This code adds an event listener to the contextmenu event, which is triggered when the user right-clicks on the web page. The preventDefault() method is called to prevent the default behavior of the event, which is to display the context menu. The window.getSelection() method is called to get the selected text, and the copyToClipboard() function is called to copy the text to the clipboard.

The copyToClipboard() function creates a temporary textarea element, sets its value to the provided text, appends it to the document body, selects the text, calls the document.execCommand('copy') method to copy the selected text to the clipboard, and removes the textarea element from the document body.

Note that this approach only works when the user selects text using the mouse, and not when they use keyboard shortcuts to copy text. Additionally, the document.execCommand() method is not supported in all browsers, so this code may not work in all situations.

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE