What is the best way to copy text from <code> and <pre> elements to the clipboard with JQuery and JavaScript?

Referencing MDN Web Docs

The HTMLInputElement.select() function is designed to highlight all text within an input field or textarea field.

This signifies that the .select() method will not function properly on elements other than input and textarea. In a scenario where I have content within code and pre tags that I want users to be able to copy by clicking on a copy button, this limitation poses a challenge.

$(document).ready(function() {
  $('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');

  $('code span.command-copy').click(function(e) {
    text = $(this).parent().select(); //.text();
    copiedText = $.trim(text);
    document.execCommand("copy");
  });

  $('pre span.command-copy').click(function(e) {
    text = $(this).parent().parent().select(); //.text();
    copiedText = $.trim(text);
    document.execCommand("copy");
  });
})
code,
pre {
  position: relative;
}

code,
pre {
  display: block;
  padding: 20px;
  background: #f2f2f2;
  color: #555755;
}

span.command-copy {
  position: absolute;
  top: 10px;
  right: 10px;
  opacity: .6;
  font-size: 20px;
  color: #555755;
}

span.command-copy:hover {
  cursor: pointer;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<h4>
  <b>Steps to install pytest</b>
</h4>
<p>
  <b>Step 1: </b>Open the terminal and type in this command:

</p>
<code class="command-copy">
        pip install pytest 
</code>
<p>Or you can upgrade your existing:
  <p>

    <pre><span></span><span class="nv">pip</span> install --upgrade pytest
<span class="command-copy"><i class="fa fa-clipboard" aria-hidden="true"></i></span></pre>

Is there a workaround for this issue? Thank you

Answer №1

In order to copy text to clipboard on click event, you can enhance your existing code with some JavaScript.

Using .select() alone will not suffice as it only selects the text without copying it, which may not meet your requirements of clicking to copy and paste.

Here are a few steps to achieve this:

  1. Create an element in the body and assign your text value to it.
  2. Utilize document.execCommand('copy'); to copy the value from the input.
  3. Once successfully copied, remove the input value from the DOM.

Feel free to run the snippet below to observe it in action.

$(document).ready(function() {
  $('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');
  
  $('code span.command-copy').click(function(e) {
    var text = $(this).parent().text().trim();
    var copyHex = document.createElement('input');
    copyHex.value = text;
    document.body.appendChild(copyHex);
    copyHex.select();
    document.execCommand('copy');
    console.log(copyHex.value);
    document.body.removeChild(copyHex);
  });

  $('pre span.command-copy').click(function(e) {
    var text = $(this).parent().text().trim();
    var copyHex = document.createElement('input');
    copyHex.value = text;
    document.body.appendChild(copyHex);
    copyHex.select();
    document.execCommand('copy');
    console.log(copyHex.value);
    document.body.removeChild(copyHex);
  });
})
code,
pre {
  position: relative;
}

code,
pre {
  display: block;
  padding: 20px;
  background: #f2f2f2;
  color: #555755;
}

span.command-copy {
  position: absolute;
  top: 10px;
  right: 10px;
  opacity: .6;
  font-size: 20px;
  color: #555755;
}

span.command-copy:hover {
  cursor: pointer;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<h4><b>Steps to install pytest</b></h4>
<p><b>Step 1: </b>Open the terminal and type in this command:</p>
<code class="command-copy">
        pip install pytest 
</code>
<p>Alternatively, you can upgrade your existing installation:<p>
<pre><span></span><span class="nv">pip</span> install --upgrade pytest
<span class="command-copy"><i class="fa fa-clipboard" aria-hidden="true"></i></span></pre>

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

Tips for locating the XPath to select an image with matching names

Could someone provide me with the XPath to click on the image <img> associated with "TM100" mentioned in the td tag? I am having difficulty selecting the image because they all have the same xpath. <tr> <td> <div id='xxx' c ...

Ways to modify the color of text when it exceeds an element's boundaries

I'm trying to figure out how to change the text color when it hovers over a black circle HTML element that is fixed to the window. I've attempted using mix-blend-mode: difference;, but I can't seem to get it to work. Ideally, I want the text ...

Something seems to be amiss with the validation functionality in jQuery

After creating a simple form with input fields and a button, I added validation to display an error message when clicking the apply button without filling out required values. However, the code is not functioning as intended. Even though error messages are ...

The hover effect on MUI TableRows is being overshadowed by the background color of the TableCell

I'm currently using @mui/material version ^5.10.1. My challenge is applying the TableRow hover behavior as outlined in the documentation. However, I have also set a background color for the first TableCell in each row, which ends up overriding the ho ...

Is the background image slowly disappearing?

Instead of using the background property for a background image, I have opted for a different style. Here is how I implemented it: <div id="bg"> <img id="bgChange" src="image/image.jpg" /> </div> This is the corresponding CSS code: ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Is there a way to adjust the input type date format to show mm/dd/yy?

My input type is set to "date" with the default format of mm/dd/yyyy. However, I would like to change it to mm/dd/yy. Is there a way to adjust the format of a date input? Date: <input type="date" id="date" name="date" value="mm/dd/yy" required/> ...

Generate and display a word document using JavaScript instead of prompting for a download

Is it possible to have a link that, when clicked, opens a print window for a .docx or PDF file instead of downloading or displaying the file directly? I attempted to achieve this with the following code snippet but encountered an error: var e = docume ...

Unable to display routerLink within innerHTML in Angular

Within my component code, there is a field named "taggy" that contains a complete anchor tag. Initially, when I rendered it in my HTML, I only saw the contents of "taggy" displayed as text "<a href="blopp/1337">hazaa<a>". Clearly, this did not ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

Adjusting the size and positioning of an image with CSS

Here is my situation: I am working with an image that is 1900 x 1600 pixels in size. I also have a div that is sized at 200 x 150 pixels. To adjust the image size, I used the following CSS: max-width:300px; max-height:300px; The height will be adjuste ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

Make the width of a table column match the width of the header

I am currently using Primeng2 datatable and I am looking to adjust the column width to match the header size. This is my HTML code: <p-dataTable #dtselfcollectmonthly [exportFilename]="exportname" [rows]="10" [value]="rawdatatrucks"> <ng-con ...

Organize Image Collection in an Asp.Net MVC Webpage

Looking to build an Asp.Net MVC 5 (Razor) view and controller that can manage a collection of images. Consider a model similar to the following (where the data is stored in a database and accessed using EF): public class Game { public Guid Id {get; se ...

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

Updated the application to Angular 6 but encountered errors when attempting to run npm run build --prod. However, running the command npm run build --env=prod was executed without any issues

Running the command npm run build -- --prod results in the following error messages: 'PropertyName1' is private and can only be accessed within the 'AppComponent' class 'PropertyName2' does not exist in type 'AppCompo ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

javascriptif the number is a whole number and evenly divisible

I am currently developing a script that tracks the distance traveled by some dogs in meters. It is basically just a gif running in a loop. What I want to achieve now is to display an image every 50 meters for a duration of 3 seconds. Here's my attempt ...

What steps should I take to address the issue with my navbar?

I've written some code that creates a hamburger icon on mobile devices. When the user clicks it, a wave effect covers the screen, but I'm facing an issue where the wave doesn't cover the input field. My query is: how can I make the input fi ...

Animating background color change with scroll in React using fade effect

Can someone help me with implementing a fading animation for changing the background color on scroll in React? I have successfully achieved the background change effect, but I'm struggling to incorporate the fading effect. import React from "reac ...