Isius
Isius

Reputation: 6974

How do I make new elements draggable with jquery?

I'm loading new elements with a form. After the elements are loaded I need to make each one draggable. According to .on doc "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."

I've tried oh-so-many variants of .on, .click, etc but so far no luck. I'm currently working with...

    $('#parent').on('change', '.thumb', function(event){
        alert('loaded');
        $('.thumb').draggable();
    });

...but, it doesn't attach to the new .thumb element. How can I accomplish this?

Edit: Here's the html...

        <input type="file" id="parent" name="files[]" multiple />
        <output> //these spans are created after files are selected from 'file'
            <span><img class=".thumb" src="..."></span>
            <span><img class=".thumb" src="..."></span>
        </output>

Upvotes: 0

Views: 1189

Answers (3)

Rafael Sedrakyan
Rafael Sedrakyan

Reputation: 2629

Try this:

$('#parent').live('change', '#child', function(event){
    alert('loaded');
    $('#child').draggable();
});

Upvotes: 0

A.P.
A.P.

Reputation: 123

There isn't enough detail for me to answer this question specifically, so I will attempt to guess what the problem is.

You are binding this function to the event "change" of an element with an id of "parent." The "change" function will only work in certain DOM elements, namely input, textarea, and select. (http://api.jquery.com/change/) This means that the change event will never fire if the element with id "parent" is anything but those three tags.

If this is the problem, I would suggest moving the .draggable() method to the same place you are adding "elements with a form."

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

When you use a plugin that requires binding it's own events and DOM manipulation from within the plugin, delegation methods like on() are useless.

You need to call the draggable() method when you load new elements such as in success callback of ajax.

If you are using load()

 $('#myDv').load( url, function(){

   /* new html has been inserted now */

    /* in case any other active draggables will only search within $('#myDiv') for new elements that need to be called*/
     $(this).find('.dragClass').draggable();

 })

Upvotes: 1

Related Questions