Reputation: 1507
Below is some code that uses jQuery. Clicking a button will copy an original rectangle.
How can I make all rectangles draggable?
CSS:
.my_rectangle {
width: 200px;
background: pink;
}
HTML:
<div id="original_rectangle" class="my_rectangle">original rectangle</div>
<button id="copy_button">Copy</button>
Javascript:
var count = 1
$("#copy_button").click(function() {
copy = $("#original_rectangle").clone()
copy.removeAttr("id").html("copy " + count).appendTo("body")
count += 1
})
(Acknowledgment: Thank you to user Haochi for the original version of the code.)
Upvotes: 1
Views: 755
Reputation: 23943
Change this:
copy.removeAttr("id").html("copy " + count).appendTo("body")
...to this:
copy.removeAttr("id").html("copy " + count).appendTo("body").draggable();
This assumes you're using the jQuery UI library.
Separately, it's a good idea to terminate your statements with semicolons. JavaScript's automatic semicolon insertion can occasionally lead to tricky bugs. The classic example:
function f(){
return
{
some : 'value'
}
}
Of course, in this example the bracket style conspires with semicolon insertion to create the ambiguity, so it's an argument against both semicolon insertion and placing opening brackets on new lines.
Upvotes: 1
Reputation: 8900
I recommend using the jQuery UI library for draggables, otherwise you will end up re-implementing much of the same thing they have done.
http://jqueryui.com/demos/draggable/
Creating a draggble would look something like this:
$("#original_rectangle").draggable();
Upvotes: 2
Reputation: 235
Consider using jQueryUI. Check out their demo of draggable to see if its what you're looking for.
Upvotes: 1
Reputation: 9173
If you use jQueryUI it would look something like this:
var count = 1
$("#copy_button").click(function() {
copy = $("#original_rectangle").clone()
copy.removeAttr("id").addClass("dragMe ui-widget-content").html("copy " + count).appendTo("body")
count += 1
})
$("dragMe").draggable();
Upvotes: 1