Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get src of dropped image from event target

I have a list of images that i can drap and drop, when dragging starts on image i store it’s URL in a state like this:

 <img
        alt="dummy-img"
        src="https://dummyimage.com/200x100/c916c9/fff.jpg"
        draggable="true"
        onDragStart={(e) => {
           setURL(e.target.src);
           //console.log(URL);
        }}
    />

When dropping it i use that state URL to display the image:

       <div
          ref={ref}
          onDragOver={(e) => e.preventDefault()}
          onDrop={(e) => {
            e.preventDefault();
            console.log(e);
            handleDrop(e);
          }}          
        ></div>

But i was wondering if i could use the event e produced by onDrop to get the URL of the image, without creating another HTML img…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to do this to see if it’s possible to drop online images directly.

>Solution :

You can use event.dataTransfer.getData('text/html') to get the HTML of the dropped image. Then, you can use a DOMParser to read the source of the image, which works both for images on the page and images dropped from other sites.

Example:

let dropArea = document.getElementById('dropArea');
dropArea.addEventListener('dragover', e => e.preventDefault());
dropArea.addEventListener('drop', function(e) {
  e.preventDefault();
  let html = e.dataTransfer.getData('text/html');
  let src = new DOMParser().parseFromString(html, "text/html")
              .querySelector('img').src;
  console.log(src);
});
<img src="https://dummyimage.com/200x100/c916c9/fff.jpg" draggable="true">
<div id="dropArea" style="height: 100px; background: dodgerblue;">Drop here</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading