Mile
Mile

Reputation: 71

How do you make prepended elements draggable

I have a code that adds elements upon the click of a button.

$(document).ready(function(){
    $("#add_txt").click(function(){
        $("body").prepend('<input class="style_txt">');
    });
});


//However when I add...

$( function() {
    $( ".style_txt" ).draggable();
  } );
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<button class="btn" id="add_txt">Add Text</button>

The element can not be dragged? Why is this?

Upvotes: 2

Views: 44

Answers (2)

Dan Kreiger
Dan Kreiger

Reputation: 5516

You could do it like this:

$(document).ready(function() {
  $("#add_txt").click(function() {
    $("body").prepend('<div class="style_text"><input /></div>');

    $(".style_text").draggable({
      start: function(event, ui) {
        $(this).data("preventBehaviour", true);
      }
    });
    $(".style_text :input")
      .on("mousedown", function(e) {
        var mdown = document.createEvent("MouseEvents");
        mdown.initMouseEvent(
          "mousedown",
          true,
          true,
          window,
          0,
          e.screenX,
          e.screenY,
          e.clientX,
          e.clientY,
          true,
          false,
          false,
          true,
          0,
          null
        );
        $(this).closest(".style_text")[0].dispatchEvent(mdown);
      })
      .on("click", function(e) {
        var $draggable = $(this).closest(".style_text");
        if ($draggable.data("preventBehaviour")) {
          e.preventDefault();
          $draggable.data("preventBehaviour", false);
        }
      });
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<button class="btn" id="add_txt">Add Text</button>

It's a rather complex answer, but it works. Note: I found this workaround in another answer.

Upvotes: 0

ewwink
ewwink

Reputation: 19184

you can't do it with input element, wrap it inside span

$(document).ready(function() {
  $("#add_txt").click(function() {
    $("body").prepend('<span><input class="style_txt"></span>');
    $(".style_txt").parent().draggable();
  });
});
span {
  padding: 5px;
  border: 1px solid #eee;
  cursor: move;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<button class="btn" id="add_txt">Add Text</button>

Upvotes: 3

Related Questions