How can I make a jquery created div be draggable?

140 views Asked by At

Hi i was wondering if there was a possible solution of creating a draggable div which is created in javascript for example:

var output = "  ";
output+= ' <div class=" image">';
output+= ' <p class="p-id"><strong>' + data.properties[i].id+ '<strong></p>';
output+= '<img class="pic" src="'+ data.staff[i].picture + '"/>';
output+= '</div>';

document.getElementById("right" ).innerHTML = output;

is there a way to make this div class=" image" draggable since im having issues with it and would like to know wether there is a possible solution. Help would be Appreciated

To make it more clear i want a method that looks similar to this code below which makes the java created <div class="image"> draggable. I Have tried this method:

$(".image ").draggable({
revert:true,

   drag:function () {
     $(this).addClass("active");
     $(this).closest(".class ").addClass("active");
   },

  stop:function () {
   $(this).removeClass("active").closest(".image").removeClass("active");
  }
});
2

There are 2 answers

0
Gerjan On BEST ANSWER

if you are using jQuery-ui then you can just add $('.image').draggable(); after you added the element to the DOM.

var output = "  ";
output+= ' <div class=" image">';
output+= ' <p class="p-id"><strong>#<strong></p>';
output+= '<img class="pic" src="#"/>';
output+= '</div>';

document.getElementById("right" ).innerHTML = output;
$('.image').draggable();
.image {
  width:100px;
  height: 100px;
  background-color: red;
}
<html>
  <head>
    <script
            src="https://code.jquery.com/jquery-3.1.1.js"
            integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
            crossorigin="anonymous"></script>
    <script
            src="http://code.jquery.com/ui/1.12.1/jquery-ui.js"
            integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30="
            crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="right"></div>
  </body>
</html>

2
Kuja On

Like this?

div {
    border: 1px solid;
    width: 200px;
    height: 200px;
    resize: both;
    overflow: auto;
    background: #d2d2d2;
}
<div>
</div>

Check this out: http://www.w3schools.com/cssref/css3_pr_resize.asp