html5 – How to drag and drop a button in a textarea?

Question:

I'm creating an email editor and it will have some macros in it, I made some examples of drag and drop using images, I would like to know if it's possible, or even if it's interesting to use buttons to be draggable.

Objective: Drag the buttons to the textarea and when releasing the button on it insert only the text contained in the button.

Example:

<button>[CODIGO_CLIENTE]</button>
<button>[NOME_CLIENTE]</button>

<br>
<br>
<textarea rows="4" cols="50">
  
</textarea>

There is this example, but it uses the draggable jQuery plugin: http://jsfiddle.net/gabrielr47/9zn03xzu/1/

Answer:

Here is a suggestion with native drag & drop (HTML5).

The idea is to associate the string you want in dragstart and then extract it in the drop to concatenate with the value already exists in the textarea .

function prepareDrag(el) {
  el.addEventListener('dragstart', e => e.dataTransfer.setData('text/plain', el.textContent))
}
[...document.querySelectorAll('button')].forEach(prepareDrag);

var textarea = document.querySelector('textarea');

textarea.addEventListener('dragover', e => e.preventDefault());
textarea.addEventListener('drop', e => {
  var data = e.dataTransfer.getData('text/plain');
  console.log(data);
  textarea.value += data;
});
div {
  padding: 30px;
  border: 1px solid black;
}
<button draggable="true">[CODIGO_CLIENTE]</button>
<button draggable="true">[NOME_CLIENTE]</button>

<br>
<br>
<textarea rows="4" cols="50">
  
</textarea>
Scroll to Top
AllEscort