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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The code currently generates the fields but they are not draggable while being clicked.
CodePudding user response:
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>