Question

Here is my code:

    $(document).ready(function () {
        var $div = $('<div>my test</div>').draggable().appendTo('body');
        $div.attr('id', 'Test');
    });

    //$('div#Test'.draggable({
    $('div').draggable({
        stop: function (event, ui) {
            var draggableId = $(this).attr("id");
            alert(draggableId);
        }
    });

While dragging the dynamically div, I expected the stop function will show alert. But it not work. What am I doing wrong?

Thank you in advance for the help!

Was it helpful?

Solution

When you create your div element you call draggable on it, but without any settings. Try this:

var draggableSettings = {
    stop: function (event, ui) {
        var draggableId = $(this).attr("id");
        alert(draggableId);
    }
}

$(document).ready(function () {
    $('div').draggable(draggableSettings); // any pre-existing divs

    // the dynamically created div
    var $div = $('<div>my test</div>', { 'id': 'Test').draggable(draggableSettings).appendTo('body');
});

Note also that the call to draggable on load needs to be placed within the document ready handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top