Reputation: 349
I have been trying to build a CMS where the contents are generated automatically and they must be draggable. For this, I have used Jquery UI to make the elements move to other positions.
The problem is that when I generate content dynamically, the jquery's draggable functionality does not work. I generated some divs dynamically with Jquery and I wish that these divs can be draggable but when I try to do it using jquery the content does not move.
If the content is not generated dynamically (static content), then the draggable works.
This is my Jquery Code:
$("#btnAddTextsBlog").click(function() {
var texts = $("#blog_text").val();
var content2 = "<div id='text1' class='ui-widget-content' style='float: left; margin-left: 30px; margin-right: 30px; margin-top: 30px; display: block;'><p style='font-size: 18px;'>" + texts + "</p></div>";
$("#main_col_blog_results").append(content2);
});
$(".ui-widget-content").draggable();
HTML CODE:
<div class="row" id="main_row_blog_results">
<div class="col-md-12" id="main_col_blog_results">
</div>
</div>
I want to make the dynamic content of the page be draggable
, any suggestion of where the error may be? How could the draggable
dynamic content be made?
Upvotes: 1
Views: 2256
Reputation: 22323
When generate div
add class draggable
after append.
var content2 = "<div id='text1' class='ui-widget-content draggable' style='float: left; margin-left: 30px; margin-right: 30px; margin-top: 30px; display: block;'><p style='font-size: 18px;'>"+texts+"</p></div>";
Or Alternative use .draggable()
whenever append. Working example below.
var content2 = "<div id='text1' class='ui-widget-content draggable' style='float: left; margin-left: 30px; margin-right: 30px; margin-top: 30px; display: block;'><p style='font-size: 18px;'>"+texts+"</p></div>";
$("#btnAddTextsBlog").click(function() {
var texts = 'Test Val';
var content2 = "<div id='text1' class='ui-widget-content' style='float: left; margin-left: 30px; margin-right: 30px; margin-top: 30px; display: block;'><p style='font-size: 18px;'>" + texts + "</p></div>";
$("#main_col_blog_results").append(content2).draggable();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id='main_col_blog_results'></div>
<input type='button' id='btnAddTextsBlog' value='Test Button'/>
Upvotes: 0
Reputation: 1431
Every time you add element, initialize draggable again.
$("#btnAddTextsBlog").click(function() {
var texts = $("#blog_text").val();
var content2 = "<div id='text1' class='ui-widget-content' style='float: left; margin-left: 30px; margin-right: 30px; margin-top: 30px; display: block;'><p style='font-size: 18px;'>" + texts + "</p></div>";
$("#main_col_blog_results").append(content2);
$(".ui-widget-content").draggable(); // initialize again
});
$(".ui-widget-content").draggable();
Upvotes: 2