I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but the draggable functionality isn't working on elements created dynamically through a function. Is there a way to make sure that the draggable method works on dynamically created elements?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Draggable Div Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.test {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div id="area" style="border: 1px solid black; width: 500px; height: 500px;"> </div>
<script>
var area = document.getElementById("area");
function duplicate(e) {
switch(e.keyCode) {
case 49:
var test = document.createElement("div");
test.classList.add("test");
test.classList.add("draggable");
console.log(test.classList)
test.style.backgroundColor = "blue";
area.appendChild(test);
break
}
}
document.addEventListener("keydown", duplicate)
$( function() {
$( ".test" ).draggable();
} );
</script>
</body>
</html>
Thanks