How to Drag and Drop button in a textarea?

Asked

Viewed 531 times

3

I am creating an email editor and it will have some macros, I made some examples of drag and drop using images, I wonder if it is possible, or even if it is interesting to use buttons to be draggable.

Goal: Drag the buttons to the textarea and when release 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 plugin draggable jQuery: http://jsfiddle.net/gabrielr47/9zn03xzu/1/

  • I think that dragging elements inside textarea is a little difficult (or impossible) unless you wanted to convert them into text, but check this out: https://answall.com/q/64329/3635 You may be able to simulate the textarea with contentEdtiable=true.

  • @Guilhermenascimento As you said, I would like to Drag an element but what goes to the textarea will only be the text, so a conversion should be made at drop time

  • I think you could edit the question to make yourself understood better, exactly what text do you want to be added? Some attribute data- or the name of the button?

2 answers

1


Here’s a hint with native drag & drop (HTML5).

The idea is to associate the string you want in dragstart and then extract in the drop to concatenate with the value already existing 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>

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.