Rafael
Rafael

Reputation: 219

Jquery-ui draggable not working after appendchild()

I'm developing a website that has a canvas and a tool box. In the tool box there are buttons to add to canvas the chosen tool (I made this way because I was not able to implement a working drag and drop). The point is exactly this, when I press the button of the tool, this tool will appear in canvas as a draggable element. But It simple doesn't work, I can make the tool appear, but It stay fixed(not able to drag It on the canvas)

My button code:

<button id="btn1" onclick="addToCanvas();"> 
  <img id="computer" src="images/myImage.png" width="40px;" height="40px;">
</button>

My javascript function for "addToCanvas()"

function addToCanvas(number){
var wrapper= document.createElement('div');
wrapper.innerHTML = '<div id="draggable" class="ui-widget-content"><img  src="images/myImage.png" width="60px;" height="60px;"></div>';
wrapper.setAttribute('id',"draggable");
wrapper.setAttribute('class',"ui-widget-content");
canvas.appendChild(wrapper);
}

Do you guys have any idea what It could be? Thanks

Upvotes: 2

Views: 754

Answers (1)

Danny
Danny

Reputation: 1759

You're creating it with the id of draggable, but that alone doesn't make it actually draggable. You need to call the jQuery function on the object, once it has been added to the DOM.

function addToCanvas(number){
   var wrapper= document.createElement('div');
   wrapper.innerHTML = '<div id="draggable" class="ui-widget-content"><img  src="images/myImage.png" width="60px;" height="60px;"></div>';

   // it appears to me these next two lines are redundant - you're already seeting their values in the innerHTML
   wrapper.setAttribute('id',"draggable");
   wrapper.setAttribute('class',"ui-widget-content");

   canvas.appendChild(wrapper);
   $('#draggable').draggable();   // <-- this is the missing piece
}

From the Draggable API found here.

Also, you have a mixture of plain javascript and jQuery UI in there - I would keep it simple and just go jQuery all the way and make my function look like this: (I removed the number parameter since you weren't using it for anything, or even passing it in on click event)

function addToCanvas() {

   var $draggable = $('<div id="draggable" class="ui-widget-content"><img  src="images/myImage.png" width="60px;" height="60px;"></div>');
   canvas.append($draggable);
   $draggable.draggable();

}

Sample JSFiddle here.

Upvotes: 1

Related Questions