lazarea
lazarea

Reputation: 1349

jQuery UI Draggable not working on child element

My goal is to create a box (a div element) inside a larger div area (let's call it 'canvas' but not to be confused with HTML's canvas element) and give the user the possibility to drag them to various parts of the canvas area. Boxes can be created by clicking a link (an <a> tag).

I am facing two issues:

  1. The first time the site loads, pressing the link does show the box for a fraction of a second but clears the canvas. I need to press the link once again for the box to appear and remain on the canvas. I added {revert: false} as the input to draggable() but didn't solve it.
  2. The box(es) that appear are not draggable.

I'm not sure where I am wrong.

$(function() {
  $(".dropdown-btn").click(function() {
    $(".canvas").append('<div class="indi-box"><div>Indicator</div><form><select id="dropdown"><option value="1">1</option><option value="2">2</option></select></form><div>');
  });
  $(".indi-box").draggable({
    revert: false
  });
});
.canvas {
  height: 50vw;
  width: 90vw;
  background-color: powderblue;
  border: 2px solid grey;
}

.indi-box {
  background-color: #336DFF;
  display: inline-block;
  padding: 0.5em;
  margin: 2px;
}

#dropdown {
  margin: 15px;
}
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<body>
  <a href="#" class="dropdown-btn">Create Box</a>
  <div class="canvas"></div>
</body>

Upvotes: 0

Views: 151

Answers (1)

r1ddler
r1ddler

Reputation: 178

It is not working because the element with class indi-box does not exist when

  $(".indi-box").draggable({
    revert: false
  });

Try this:

  $(".dropdown-btn").click(function() {
    $(".canvas").append('<div class="indi-box"><div>Indicator</div><form><select id="dropdown"><option value="1">1</option><option value="2">2</option></select></form><div>');
    $(".indi-box").draggable({
      revert: false
    });
  });

Upvotes: 1

Related Questions