JaredH20
JaredH20

Reputation: 368

jQuery Draggable only allowing 1 image to be draggable

I have a page full of images, album artwork to be precise. I have added code to make it draggable and it will only allow me to drag the first image on the page.

Why is this?

 $(document).ready(function () {
            $("#draggable").each(function () {
                $(this).draggable({
                    revert: function (dropped) {
                        var dropped = dropped && dropped[0].id == "droppable";
                        if (!dropped);
                        return !dropped;
                    }
                });
            });

            $("#droppable").droppable({
                drop: function (event, ui) {
                    var AlbumToAdd = ui.draggable.data("id");
                    if (AlbumToAdd != '') {
                        // Perform the ajax post
                        $.post("/ShoppingCart/DragToCart", { "id": AlbumToAdd },
                            function (data) {
                                // Successful requests get here
                                // Update the page elements
                                $('#cart-total').text(data.CartTotal);
                            });
                    }
                }
            });

        });

Comment if you need to see more code

Upvotes: 1

Views: 379

Answers (1)

Jules
Jules

Reputation: 7223

Usually id's are supposed to be unique. So doing $("#draggable").each... is usually not a good practise. Changing this into a class selector should solve the issue.

So transform it into:

$(".draggable").each(function () { ...

And your html into

<div class="draggable" class="ui-widget-content">
    <p>Drag me around</p>
</div>

You can see my working example (simplified) here.

Upvotes: 2

Related Questions