Как реализовать функционал Copy Code для копирования в буфер обмена?

Подскажите как реализовать функционал copy code? При нажатии на кнопку copy code текст Witcher должен быть скопирован в буфер обмена для дальнейшей вставки.

'use strict';

const code = document.querySelector('.promo__code-text');
const codeText = code.textContent;
const copyCodeBtn = document.querySelector('.js-copy-code');

const handleCopyCodeBtnClick = e => {
  document.execCommand('copy');

  console.log(codeText);

  e.preventDefault();
};

copyCodeBtn.addEventListener('click', handleCopyCodeBtnClick);
.promo__code {
  padding: 10px 20px;
  font-family: Arial;
  border-width: 1px;
  border-color: #464646;
  border-style: dashed;
  border-top-left-radius: 40px;
  border-bottom-left-radius: 40px;
}

.promo__code-wrap {
  display: flex;
  margin-bottom: 20px;
  justify-content: center;
}

.promo__code-text {
  font-size: 14px;
  line-height: 1;
  text-align: center;
  letter-spacing: 4px;
  text-transform: uppercase;
  color: #f73427;
}

.promo__copy-code {
  padding: 10px 20px;
  font-family: Arial;
  font-size: 11px;
  line-height: 1;
  color: #222;
  text-transform: uppercase;
  background: none;
  border-width: 1px;
  border-color: #464646;
  border-style: dashed;
  border-top-right-radius: 40px;
  border-bottom-right-radius: 40px;
  transition: all 0.2s linear;
  cursor: pointer;
}

.promo__copy-code:hover {
  background: rgba(255, 255, 255, 0.2);
}
<form class="promo__code-wrap">
  <div class="promo__code">
    <span class="promo__code-text">Witcher</span>
  </div>
  <!-- <div class="promo__copy-code">Copy code</div> -->
  <button class="promo__copy-code">Copy code</button>
</form>


Ответы (1 шт):

Автор решения: Mr_CatYT
function copyToClipboard() {
  /* Get the text field */
  var copyText = document.getElementsByClassName("promo__code-text");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}

или

const copyToClipboard = () => {
  /* Get the text field */
  var copyText = document.getElementsByClassName("promo__code-text");
    
  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
→ Ссылка