Skip to content
Advertisement

How can one use JS to add a draggable field?

What do I need to change in my code so that it generates draggable fields. This is what I have tried so far:

(function() {
  var counter = 0;
  var b = document.getElementById('b');
  var l = document.getElementById('l');
  var addInput = function() {
    counter++;
    var input = document.createElement("input");
    input.id = 'input-' + counter;
    input.className = 'd';
    l.appendChild(input);
  };
  b.addEventListener('click', function() {
    addInput();
  }.bind(this));
})();

$('.d').draggable({
  cancel: null
});
$('.d input').click(function() {
  $(this).focus();
});
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>

<script src="https://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>

<button id="b" type="button">Add</button>
<br>

<label id="l" action="">
</label>

The code currently generates the fields but they are not draggable while being clicked.

Advertisement

Answer

You’re trying to set ‘draggable’ on the elements before they exist.

Try setting it (and your click handler) after you insert them into the DOM:

(function() {
  var counter = 0;
  var b = document.getElementById('b');
  var l = document.getElementById('l');
  var addInput = function() {
    counter++;
    var input = document.createElement("input");
    input.id = 'input-' + counter;
    input.className = 'd';
    l.appendChild(input);
    $(input).draggable({
      cancel: null
    })
    $(input).click(function() {
      $(this).focus();
    });
  };
  b.addEventListener('click', function() {
    addInput();
  }.bind(this));
})();
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>

<script src="https://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>

<button id="b" type="button">Add</button>
<br>

<label id="l" action="">
</label>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement