Shkelqim Maxharraj Shkelqim Maxharraj - 6 months ago 34
Javascript Question

Add an element to page. Than drag it

I'm adding an element on a page but i can't drag it. Can anyone help me out with this.This is my code:


<div class="mainDiv">
<input type="button" value="clickme" id="clickme">


#dragme {
height: 100px;
width: 100px;
background-color: red;
cursor: pointer;

And JavaScript with jQuery

$("#clickme").click(function() {
$(".mainDiv").append("<div id='dragme'>Drag me</div>");


Demo Here


Firstly, $.draggable is a method from jQuery UI package, so if you want to use it, you will have to include it.

Secondly, when you call $("#dragme").draggable(), the element is not added to the DOM yet and therefore $("#dragme") will return nothing. You will have to call this function after you add the #dragme element in the page.

Here is a working update of your code: