1

so on a page there are divs like <div id='3' type='touchMyDiv'> that are draggable. They can be dragged to another div.

When dropped there, JavaScript does a forward to an URL that contains the id of the dropped div. Example: /?action=deleteTable&tableID=3
Works super nice so far.
(Yes it only works with the id if user is logged in)

But for some reason I now need to make difference between some divs by the type (or name also possible if better)

Like <div id='3' type='touchMyDiv'> and <div id='6' type='otherType'>

So my question is: How can I get the type of the dropped div in JavaScript (to use it as a variable afterwards)

How to change the drop function to get the type?

function allowDrop(ev) {
  ev.preventDefault();
}
function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var contentID = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(contentID));
    window.location.href = "/?a=deleteTable&tableID=" + contentID;
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Chris98
  • 15
  • 4
  • 1
    div has no attribute `type`, you should use `data-type` instead. https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes – Timothy Alexis Vass Nov 15 '21 at 14:48
  • Does this answer your question? [Get HTML5 custom data attributes from dragged element](https://stackoverflow.com/questions/27958738/get-html5-custom-data-attributes-from-dragged-element) – Heretic Monkey Nov 15 '21 at 14:49
  • 1
    Does this answer your question? [How can I get the values of data attributes in JavaScript code?](https://stackoverflow.com/questions/33760520/how-can-i-get-the-values-of-data-attributes-in-javascript-code) – Timothy Alexis Vass Nov 15 '21 at 14:49

1 Answers1

2

Similar to what is done with the id, you can :

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
  ev.dataTransfer.setData("type", ev.target.getAttribute("type"));
}

function drop(ev) {
    ev.preventDefault();
    var contentID = ev.dataTransfer.getData("text");
    var contentType = ev.dataTransfer.getData("type");
    ev.target.appendChild(document.getElementById(contentID));
    window.location.href = "/?a=deleteTable&tableID=" + contentID;
}

Note that type is not a valid attribute for the div element. You should consider using data attributes instead.

Tom
  • 4,972
  • 3
  • 10
  • 28
  • 1
    You should add a disclaimer that there is not `type` attribute on most HTML elements and for custom attributes, they should be prefixed with data to avoid collisions and to be valid HTML. For example, `data-custom-attr` – Ruan Mendes Nov 15 '21 at 14:57