I have a draggable element that is dynamically generated by jQuery. I have a background image within the div. How can I bind the element so it never goes outside the div?
Here's the code: jsfiddle.net.
$(document).ready(function () {
$("button").click(function () {
$("#currentimage").append('<img id="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
$("#dragable").draggable();
});
});
You can add containment: 'parent'. Also you have to add class dragable not id. Id must be unique. So that you can click the button more than one time.
Try:
$(document).ready(function () {
$("button").click(function () {
$("#currentimage").append('<img class="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
$(".dragable").draggable({
containment: 'parent'
});
});
});
DEMO
Use containment to restrict it container
containment: $('#currentimage')
FYI
ID must be unique
.append('<img id="dragable"
Read Two HTML elements with same id attribute: How bad is it really?
you are adding images with same id.
.append('<img class="dragable"
Than use
$(".dragable").draggable();
$(document).ready(function () {
$("button").click(function () {
var el = '<img src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />';
$("#currentimage").append($(el).draggable({ containment: $("#currentimage") }));
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With