-2

my HTML is:

<div>
   <img src="random image (doesn't matter)"></img>
</div>

How would I make my div draggable like setting draggable = "true"; in html but I am looking for a css only alternative.

What I have tried:

  1. I had a look at https://css-tricks.com/books/greatest-css-tricks/draggable-elements/ but this answer seem too complex and I feel like there could be a better solution.
  2. Another question (Setting html tag attributes from css) was looking at setting a HTML attribute in css (in this case draggable) and I don't believe that it is possible looking at the answers.
tisme
  • 7
  • 6
  • Dragging is not a CSS feature it requires JS. The CSS hack uses the `resize` CSS Property but it does not work as cleanly and freely as the JS solution. – tacoshy Jan 31 '23 at 08:06
  • There is no such thing as a closing `` tag. Remove that. – Rob Jan 31 '23 at 08:52
  • dragging is behavior, not presentation, that should be done on JS, not CSS – Eduardo Wada Jan 31 '23 at 09:01
  • @EduardoWada I'm not asking should it be done, I'm asking could it be done. – tisme Jan 31 '23 at 09:03
  • @Rob how much does it matter? my code works perfectly fine with it. – tisme Jan 31 '23 at 09:07
  • Your markup is invalid. How often do you write invalid code and think it's OK to do that? – Rob Jan 31 '23 at 09:11
  • @Rob Can you explain to me why it isn't ok? It doesn't negatively effect the rest of my file so it doesn't seem to be an issue to me, Is it just bad practice? – tisme Jan 31 '23 at 09:15
  • Why don't you throw `` into it also. It's the same gibberish to a browser as `` is because that tag doesn't exist either. Why do you want to feed gibberish to browsers? They will ignore it as junk just like they are ignoring your tag now. So remove it! – Rob Jan 31 '23 at 14:53
  • @Rob This is actually a really good point, thanks for enlightening me! – tisme Feb 01 '23 at 05:25

1 Answers1

0

HTML elements can't be made draggable using CSS only. You will need to use JavaScript to make an element draggable. You can make use of the HTML5 draggable attribute for this:

<div draggable="true">Your Content Here</div>

You can also use JavaScript libraries such as jQuery UI to make elements draggable:

$( "#yourElement" ).draggable();

Or use vanilla JavaScript and interact with the HTML5 drag & drop API:

const yourElement = document.querySelector('#yourElement');

yourElement.addEventListener("dragstart", function(event) {
  event.dataTransfer.setData("text", event.target.id);
});

Note: that there are many ways to make elements draggable and the exact implementation depends on your requirements and the complexity of the drag-and-drop interactions you want to support.

Mahdi D
  • 51
  • 7