gretagremlin
gretagremlin

Reputation: 33

How to get textarea's cursor move to the end of the highlighted text on drag and drop?

When I drag and drop the image into the textarea, the text is highlighted.
Is there a way to have the textarea's cursor move to the end of the highlighted text?

document.querySelectorAll('.emoteImage').forEach((emoteImage) => {
  emoteImage.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData('text', emoteImage.alt);
    event.effectAllowed = "copy";
  });
});
img {
  width: 100px;
}
<div class="emote">
<img src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fpaomedia%2Fsmall-n-flat%2F512%2Fcat-icon.png&f=1" alt="emote1" title="emote1" class="emoteImage">
</div>


<textarea></textarea>

Upvotes: 0

Views: 286

Answers (1)

Mehdi Ayari
Mehdi Ayari

Reputation: 548

i added a "dragEnd" event to move the cursor to the end of the highlighted text. Hope it helps :)

var element = document.getElementById("textArea");

document.querySelectorAll('.emoteImage').forEach((emoteImage) => {
  emoteImage.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData('text', emoteImage.alt);
    event.effectAllowed = "copy";


});

emoteImage.addEventListener( 'dragend', function( event ) {
    var end = element.selectionEnd ;
    element.focus();
    element.setSelectionRange(end,end);
});

});
img {
  width: 100px;
}
<div class="emote">
<img src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fpaomedia%2Fsmall-n-flat%2F512%2Fcat-icon.png&f=1" alt="emote1" title="emote1" class="emoteImage">
</div>


<textarea id="textArea" ></textarea>

Upvotes: 1

Related Questions