Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!