3

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();
    });
});
laaposto
  • 11,835
  • 15
  • 54
  • 71
Anni
  • 142
  • 2
  • 16

2 Answers2

2

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

laaposto
  • 11,835
  • 15
  • 54
  • 71
1

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") }));
    });
});
Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107