Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Element href Right Before Drag

I'm creating an extension that allows me to drag photo links in some website that doesn't allow it. The element (photoCell) has a default href of "javascript://" and has a child element (photo) which holds the image.

I want to be able to change the href of the parent element to the src of the child image so when i drag, i drag the URL of the child image. (This works if i do it without a drag listener but then when i click on an element it loads the image and not the expected javascript function). So i need to change the href back to "javascript://" after drag is done.

However, even though the href changes the dragged URL still is "javascript://"

function dragstart() {
    this.href = this.children[0].src;
}

function dragend() {
    this.href = "javascript://";
}

function doForPicturedesk() {
    var gallaryCells = document.getElementsByClassName("gallery-cell");
    for (var i = 0; i < gallaryCells.length; i++) {
        var gallaryCell = gallaryCells[i];
        var photoCell = element.children[0];    
        photoCell.addEventListener("dragstart", dragstart);
        photoCell.addEventListener("dragend",dragend);
    }
}

Here's a sample of the HTML

<div class="gallery-cell jg-entry entry-visible" style="width: 534px; height: 345px; top: 10px; left: 10px;">
    <a href="javascript://" onclick="openPictureDetail('343563491-516813675371465101')" class="gallery-cell__link gallery-cell__image--hoverable">
              <img id="thumb_343563491-516813675371465101" class="gallery-cell__image " src="/bild-disp/diasdb/thumbnailextl.action?ref=343563491-516813675371465101&amp;w=false" onerror="correctMissing(this, '343563491-516813675371465101');" style="width: 534px; height: 356px; margin-left: -267px; margin-top: -178px;">
    </a>
</div>
like image 726
Rafat Mahmoud Avatar asked Sep 19 '25 07:09

Rafat Mahmoud


1 Answers

I didn't think was possible, but what do I know. All you have to do is use dataTransfer.setData to achieve your goal. Try it below:

let anchor = document.querySelector('a');
anchor.ondragstart = function(event) {
  let urlWeWant = 'https://www.example.com';
  event.dataTransfer.types.forEach(type => {
  
  //Note that all you HAVE to do for this to work is:
  //event.dataTransfer.setData(type, urlWeWant);
  //BUT, I think checking the type and replace HTML is better
  
    if (type.includes('html')) {
      let clone = event.target.cloneNode(true);
      clone.href = urlWeWant;
      let dataHTML = clone.outerHTML
      event.dataTransfer.setData(type, dataHTML);
    } else {
      event.dataTransfer.setData(type, urlWeWant);
    };
  });
};
<a href='javascript:void(0);'>Drag Me Into Another Window :)</a>
like image 65
quicVO Avatar answered Sep 20 '25 20:09

quicVO