-1

I want the user to be able to move a HTML element around inside another by dragging with the mouse. (Example, move the red square inside the yellow square)

<div style="width:100px;height:100px;background-color:yellow">
<div style="width:10px;height:10px;background-color:red">
</div>
</div>

4
  • There is some support for drag and drop in HTML5, but I think to get what you want, you'd have to add in a JavaScript framework. Something like Draggable in jQuery UI (jqueryui.com/draggable) comes to mind. Is that okay? Aug 14, 2016 at 16:44
  • I'll be using JS, though I'd like to keep the code relatively short. I won't be able to use jQuery though.
    – Bob Pickle
    Aug 14, 2016 at 16:48
  • found this jsfiddle link. pure JS draggable example. jsfiddle.net/tovic/Xcb8d Aug 14, 2016 at 16:59
  • @BobPickle Cool. If the answer I've added below solves your question, feel free to click the checkmark to accept. If it doesn't quite do that, just let me know and I can revise. Aug 14, 2016 at 17:48

1 Answer 1

1

Here's an example using a simple and popular library called Draggabilly which doesn't require jQuery.

window.onload = function() {
  var draggie = new Draggabilly('.draggable', {
    containment: true
  });
};
.container {
  background-color: yellow;
  height: 100px;
  width: 100px;
}

.draggable {
  background-color: red;
  height: 10px;
  width: 10px;
}
<!-- Based on the Draggabilly containment example using jQuery - http://codepen.io/desandro/pen/azRmYv -->

<script src="https://npmcdn.com/[email protected]/dist/draggabilly.pkgd.min.js"></script>

<div class="container">
  <div class="draggable"></div>
</div>

Note: Should you decide to use jQuery, the JavaScript could be simplified:

$(function(){
  $('.draggable').draggabilly({
    containment: true
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.