Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set bounds for draggable element

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();
    });
});
like image 527
Anni Avatar asked Feb 22 '26 13:02

Anni


2 Answers

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

like image 98
laaposto Avatar answered Feb 24 '26 03:02

laaposto


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.


You can use class
.append('<img class="dragable"

Than use

$(".dragable").draggable();


Fiddle Demo
$(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") }));
    });
});
like image 21
Tushar Gupta - curioustushar Avatar answered Feb 24 '26 03:02

Tushar Gupta - curioustushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!