Shkelqim Maxharraj Shkelqim Maxharraj - 1 year ago 91
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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download