Copying large blocks of text to the clipboard is not functioning properly

I have a situation where my script works perfectly fine when I click a single button to copy text to the clipboard. However, when I try to implement multiple buttons for copying different pieces of text, it doesn't seem to work as intended.

Can someone please help me figure out what is causing this issue? How can I modify my script to allow for functionality with more than one button and text?

var copyBtn = document.querySelector('.js-copybtn');
if (copyBtn) {
    copyBtn.addEventListener('click', function(event) {
        var copyText= document.querySelector('.js-copytext');
        var range = document.createRange();
        range.selectNode(copyText);
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
        } catch(err) {

        }
        window.getSelection().removeAllRanges();
    });
}  
<div class="context">
<span class="js-copytext"><p>Text 1</p></span>
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>
    <div class="context">
    <span class="js-copytext"><p>Text 2</p></span>  
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>

Answer №1

To access all the buttons and add a click event listener, we can iterate through each button using `querySelectorAll('.js-copybtn')`. Once the button is clicked, we can grab the previous sibling element by utilizing the `previousElementSibling` property.

var copyBtns = document.querySelectorAll('.js-copybtn');
if (copyBtns && copyBtns.length) {
copyBtns.forEach((copyBtn) => {
    copyBtn.addEventListener('click', function(event) {
    console.log(copyBtn);
        var copyText= copyBtn.previousElementSibling;
        var range = document.createRange();
        range.selectNode(copyText);
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
        } catch(err) {

        }
        window.getSelection().removeAllRanges();
    });
});
}
<div class="context">
<span class="js-copytext"><p>Text 1</p></span>
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>
    <div class="context">
    <span class="js-copytext"><p>Text 2</p></span>  
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>

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

The primary text is getting truncated when an ion-note is placed inside an ion-list

I'm currently working with Ionic 3 and attempting to create a list of events where the event name appears on the left and the event note (start time) appears on the right using an ion-note. Below is the code snippet: <ion-list *ngIf="events.len ...

Utilizing the power of jQuery's $.ajax method to trigger a JavaScript function

Below is the code snippet I am working with: var twitterUrl = escape("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + username); $.ajax({ type: "GET", url: "twitter.js?url=" + twitterUrl, dataType: "json", success: fun ...

What are some ways to expand the width and increase the spacing of bootstrap cards?

On my website, I have created Bootstrap cards that are displayed on two different pages. One set of cards is shown on the landing page, where I am looking to increase the spacing between them. The other set appears on the books page, and I want to make t ...

AngularJS and JQuery validated

I'm looking to achieve something similar to what was discussed in this thread: Angularjs directive wrapping ng-repeat Although I can make it work as shown in the thread, I encounter an issue when updating the dirs array using Angular (for example, w ...

Using AngularJS ng-repeat to pass href links

I am facing an issue with displaying hyperlinks in a list of messages obtained from server response using AngularJS. $scope.messages = [] When a button is clicked, the content of a text area is added to the array using ng-click method. This message is th ...

What is the method to choose the following CSS element?

There are two div elements in my HTML code: <body> <div id="one"></div> <div></div> </body> I am looking to hide the div elements after the one with id="one" using CSS. I attempted this method: #one:after{display: ...

Incorporate dynamic interval transitions to the carousel rotation

I'm currently working on implementing a carousel with 'Next' and 'Previous' buttons that slide through images. However, I've been struggling to get the auto-slide feature to work at regular intervals. If anyone has any sugges ...

jQuery form isn't submitting

I am facing an unusual issue where my form is not sending any data, yet the page (which should only display when the data is sent) is being shown. Here is the code I am using: [..] if(form == true){ var gender = $("input[@name='rgen ...

Placement of Buttons Inside a Division Tag

Is there a better way to align button 3 & 4 in a vertical column next to button 1 & 2 without using tables in CSS? See the working example below: https://jsfiddle.net/Jaron787/0te3cs66/1/ Code: HTML <div id="lse" class="display"> <di ...

Guide to sending DevExtreme data grids to ASP.NET MVC controllers

Currently, I am utilizing a datagrid with DevExtreme. I am wondering how I can pass the datagrid to my controller in ASP.NET MVC. In my view, I have attempted the following: @using (Html.BeginForm("action-name", "controller-name", FormMethod.Post)) { ...

Convert a PHP MySQL query into JSON format

I am facing an issue with a $json variable in my code. It seems that my php query is not getting encoded into the $json variable properly. $sql = "SELECT `$column`, `Year`, `Month` FROM unemployed WHERE year BETWEEN ? AND ? and month= ?"; $stmt = $conn-&g ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

use node.js to remove any duplicate id's from a JSON array and then concatenate the unique id's

Check out how newData is printed in the code snippet below: var newData = (JSON.parse(jobData)); console.log(newData); Currently, it contains 5 values which may vary. [{ mode: daily, id: '71' os: 'Win37' }, { mode: da ...

Utilize JQuery to extract data from an Ajax XML response

Trying to work with an XML document using JQuery. The XML content is fetched through an Ajax call: $.ajax({ url: address, type: 'GET', dataType: 'xml', success: function(data) { console.log(data); } }); When the request i ...

What is the functionality of the "respond_with_navigational" feature?

Currently, I am integrating Devise and DeviseInvitable to handle authentication in my application. However, I'm facing challenges when trying to incorporate AJAX functionality into InvitationsController#update. The structure of the controller in Devis ...

Tips for highlighting the sticky subnav menu option as you scroll

Currently utilizing intersection observer to toggle the visibility of the sticky navbar and make the scroll bar sticky. I am now looking to add a feature where the sub nav options highlight with color as we scroll, focusing on the container with a specific ...

What is the best way to save and retain cache data for an audio file?

I have a website where I am using an audio file in .swf format. This audio file can be turned on and off with the options provided: AUDIO ON and AUDIO OFF. However, I am facing the issue that the audio keeps playing repeatedly even after being turned off. ...

Generating safe HTML output in PHP requires adding 4 spaces before the code

I'm currently designing a form that generates basic HTML and other plain text output for users to copy and paste into a content management system. For setting up the variables, I follow this structure: $date1 = $_POST['date1']; $city1 = $_ ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

Trouble arises when using jslider alongside prototype and implementing noConflict for jQuery

Currently facing a conflict between prototype.js and jQuery.js while attempting to incorporate jSlider, which relies on the jQuery library. I attempted to resolve this by including jQuery.noConflict() at the conclusion of jquery.js and modifying $._roundN ...