Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code:

The issue I am facing is that it only copies the URL on the second attempt and then starts stacking up the clicks, so on the third click it shows that it was clicked three times. Can someone help me understand why this is happening? What am I missing in my implementation?

<div id="dd" class="dropdown form-group position-relative col-12 col-md-6 save-dialog__form-group">
      <label for="dropdown" class="col-6 col-md-3 editor-wrapper__label">Select Image:</label>
      <div class="col-6 col-md-9">
        <a data-flip="false" data-boundary="dd" href="#" class="dropdown-toggle" data-toggle="dropdown">Images</a>
        <ul class="dropdown-menu dropdown-menu-down dropdown-menu-right">
          <li id="{{ 'image-copy-' + i }}" (click)="copyToClipboard($event)" *ngFor="let availableImage of imageOptions; let i = index" class="image-option line-item">
            <div class="image">
              <img src="{{ availableImage.relLink }}" />
            </div>
            <div class="mark-down example raw-code">
              {{ availableImage.markDown }}
            </div>
          </li>
        </ul>
      </div>
    </div>

    copyToClipboard(event) {
    var lineItem = document.getElementsByClassName('line-item');
    var lineItemLength = lineItem.length;
    for (var i = 0; i < lineItemLength; i++) {
      lineItem[i].addEventListener('click', function () {
        console.log(this.id);
        var el = document.getElementById(this.id);
        el.setAttribute('contenteditable', 'true');
        el.focus();
        document.execCommand('selectAll');
        document.execCommand('copy');
        el.setAttribute('contenteditable', 'false');
        el.blur();

      }, false);

    }
  }

Answer №1

After some trial and error, I managed to overcome this challenge by implementing the following code snippet:

copyToClipboard(event) {
    var target = event.target || event.srcElement || event.currentTarget;

    target.setAttribute('contenteditable', 'true');
    target.focus();
    document.execCommand('selectAll');
    document.execCommand('copy');
    target.setAttribute('contenteditable', 'false');
    target.blur();
  }

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

Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use var viewModel = this; employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functio ...

The parameter type SetStateAction<MemberEntityVM[]> cannot be assigned the argument type Promise<MemberEntityVM[]> in this context

I am looking to display a filtered list of GitHub members based on their organization (e.g., Microsoft employees). Implementing React + TS for this purpose, I have defined an API Model which represents the structure of the JSON data from the GitHub API: ex ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

steps for adding a progress bar in an ag-grid table

I am looking to add a progress bar in an ag-grid table column. I have searched the ag-grid documentation section but have not found any information. Are there any other websites or resources that might provide insight on how to implement this? Thank you ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

How do you call the breeze from Angular, whether it be in a service or controller? Can

I am currently working on an angular project where I am creating a form that retrieves data from a stored procedure using $http get in an angular service. My goal is to databind some dropdown lists in the filter of this html form. The data is stored in a v ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

Cutting Out Sections of a List

I'm currently working on an app that involves looking up and navigating to specific locations. I've encountered an issue with the coordinates in my code containing a ',0' at the end, which is not compatible with Google Maps. Manually re ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

Application frozen after printing <div>

I'm currently working on a project for a client and I have encountered an issue that I would appreciate some guidance on. My task involves printing the contents of a specific div on the website. After finding a solution in a previous post, I implement ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

Textarea not displaying default values when ng-model is applied

My Angular application includes a textbox in the following format: <div class="panel-body text-center"> <textarea id="mytext" class="form-control" rows="4">John,2 Jane,3 John,4 Jane,5 </textarea> </ ...

The access to the HTTP request has been restricted

Currently, I am developing multiple applications that need to communicate with each other. To test these apps, I am using both Chrome and Firefox browsers. Strangely, the issue persists in both browsers. The issue at hand: In one of my applications (let& ...

Upon clicking, the reset function will be triggered

I have a jQuery code that includes a click event on td elements. After clicking on a td, an input field with text appears and the focus is set at the end of the text. However, I want to remove the focus after the initial click so that I can click in the ...

What are the steps to implement $navigateTo() in a NativeScript Vue application?

What could be causing $navigateTo(Page) to not work? Visit this link for more information ...

Tips for adding spacing when the sidebar collapses and expands in a React application

I am attempting to achieve a layout where the body adjusts its space when the sidebar collapses and expands. Here is how it appears when the sidebar expands: see expanded sidebar here And this is how it looks when the sidebar collapses: see collapsed s ...

What is the best approach for testing a component that makes use of React.cloneElement?

My main component fetches children using react-router in the following manner: class MainComponent extends Component { render() { return ( <div> {React.cloneElement(children, this.props.data)} </div> ) } } I a ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Guide on dynamically loading email contacts options in selectize.js

I have been working with selectize.js to create an email contacts feature. However, I am facing an issue where the mail list retrieved from the database is displaying as undefined in selectize. Strangely, when I manually enter the return value, everything ...