Skip to content
Advertisement

Copy to clipboard javascript (no jQuery)

I have an Angular 9 app which I need to get a copy to clipboard of url copied when clicked. This is what I have so far:

It copies but not on first attempt only on second attempt is it consoled. Then the clicks stack up so the third click it shows it was clicked 3 times. Why? What am I doing wrong here?

<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);

    }
  }

Advertisement

Answer

I was able to resolve this issue by using the code below:

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();
  }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement