Home > Software engineering >  How can I make an element draggable only on one point?
How can I make an element draggable only on one point?

Time:09-18

I have a parent div (like "#strip17") with several child divs. Many of those child divs contain each one canvas on which the user should be able to draw stuff using his mouse. Except for the last child div, which should be the point where the user is able to grab the parent div and drag it around.

This whole (parent) div needs to be draggable, as such that the user grabbs it at the "grab"-child and drops it whereever it is needed. I need some kind of 'handle' for dragging the parent div around, if you like.

My problem here: I can only call .draggable() on either the parent child, which means that the user isn't able to draw on any of the canvas elements inside any child div (as drawing is interpreted as dragging), or I call .draggable() on the drag-child-div (".camber-move"), which would mean that only this div is moving and the rest of the parent div would stay where it is - drawable though.

I suppose, this should be doable by calling .draggable() on ".camber-move" and somehow convincing jQuery-UI to not only move the ".camber-move" div, but also its parent "#strip17". But how?

// '#<newStripID>' is the ID of the parent element
// '#<newStripID> .camber-move' is the ID of the element which should be the 'grab-handle'
$('#'   newStripID).draggable({
     "containment": "#content"
});

html:

<div id="strip17">
    <div class="strip-camber-1"><canvas></canvas></div>
    <div class="strip-camber-1"><canvas></canvas></div>
    <div class="strip-camber-1"><canvas></canvas></div>
    <div class="strip-camber-1"><canvas></canvas></div>
    <div class="camber-move"></div>
</div>

CodePudding user response:

Consider the following Demo: https://jqueryui.com/draggable/#handle

You can apply this to your example:

$(function() {
  $("#strip17").draggable({
    containment: "#content",
    handle: "div.camber-move"
  });
});
.strip-camber-1 {
  border: 1px solid #CCC;
}

.camber-move {
  border: 2px solid #222;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="strip17">
  <div class="strip-camber-1"><canvas></canvas></div>
  <div class="strip-camber-1"><canvas></canvas></div>
  <div class="strip-camber-1"><canvas></canvas></div>
  <div class="strip-camber-1"><canvas></canvas></div>
  <div class="camber-move"></div>
</div>

  • Related