Skip to content
Advertisement

javascript ondrag when pressing itself

Inside the div I have a set of p elements. I want to drag the selected element to the input Example:

var input = document.getElementById("test");
input.addEventListener('drop', function (event) {
    event.preventDefault();
    var textData = event.dataTransfer.getData('text'); // get the dragged value
    var oldval = event.target.value; // get the old value in the input
    var newval = oldval + textData; // add it with the value which is dragged upon
    event.target.value = newval; // change the value with the new value
});
document.querySelector('[draggable="true"]').addEventListener('dragstart', function(e){
  e.dataTransfer.setData('text', e.target.innerHTML);
});
<input id="test" placeholder='drag here'/>

<div>

<p draggable="true"> Tag 1</p>

<p draggable="true"> Tag 2</p>

<p draggable="true" > Tag 3</p>

</div>
I want to transfer the text from the p element to the input when dragging, but in a multiple way, for all the p elements

How, when dragging any of the multiple elements, get the text from the p element and place it in input, and switch between them in case another element is selected via JavaScript or JQuery

Advertisement

Answer

With querySelector you only target the first element, use querySelectorAll to get a list of all paragraphs, then bind the event to each of the paragraphs

var input = document.getElementById("test");
input.addEventListener('drop', function(event) {
  event.preventDefault();
  var textData = event.dataTransfer.getData('text'); // get the dragged value
  var oldval = event.target.value; // get the old value in the input
  var newval = oldval + textData; // add it with the value which is dragged upon
  event.target.value = newval; // change the value with the new value
});
document.querySelectorAll('[draggable="true"]').forEach(paragraph => {
  paragraph.addEventListener('dragstart', function(e) {
    e.dataTransfer.setData('text', e.target.innerHTML);

  })
});
<input id="test" placeholder='drag here' />

<div>

  <p draggable="true"> Tag 1</p>

  <p draggable="true"> Tag 2</p>

  <p draggable="true"> Tag 3</p>

</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement