I am currently working on making dynamically created divs draggable. While I have successfully achieved this with pre-existing div elements as shown below:
<div>
This can be dragged around, but outputs cannot?!
</div>
the issue arises when I try to make newly created divs draggable using the addElement() function.
To provide more context, my goal is to allow users to input text, which will then be displayed on the screen and able to be dragged around.
Here is the full code snippet:
function addElement () {
var text = document.getElementById("input").value;
// creating a new div element
var newDiv = document.createElement("div");
// adding content to the new div
var newContent = document.createTextNode(text);
// appending the text node to the newly created div
newDiv.appendChild(newContent);
// inserting the new element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
document.getElementById("input").value = " ";
}
$( function() {
var div = document.getElementsByTagName('div');
$( div ).draggable();
} );
div { width: 150px; height: 150px; padding: 0.5em; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<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>
</head>
<body>
<input id="input"type="text" placeholder=" text">
<button onclick="addElement()" >Input</button>
<p>Outputs:</p>
<script src="script.js"></script>
</body>
</html>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>