Sergey  Alekseev
Sergey Alekseev

Reputation: 37

Why append elements not a draggable?

I make all elements with an "image" class draggable.
Then I append more "image" elements to the page.
Why aren't the appended elements draggable?

$(function() {

  $('.image').draggable(); //Draggable image (Jquery UI)

  $('.button').click(function() { //append more image
    $('body').append('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">')
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>

<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">
<button class="button">Append image</button>

View on JSFiddle

Upvotes: 0

Views: 59

Answers (3)

Matthew Lymer
Matthew Lymer

Reputation: 977

Newly added elements will not be automatically drag-able (only those elements existing initially).

Inside your function, try re-declaring that the element will be drag-able, AFTER it is created:

$('.button').click(function(){
    $('body').append('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">');
    $('.image').draggable();
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337700

You're instantiating the draggable() plugin on the .image elements at load. Any elements added to the DOM after that will need the plugin instantiating on them once they are created. Try this:

$('.image').draggable();

$('.button').click(function() {
    var $img = $('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">').appendTo('body');
    $img.draggable();
});

Upvotes: 1

IrkenInvader
IrkenInvader

Reputation: 4050

You need to call .draggable(); on the newly created image on every button click.

$(function(){

  $('.image').draggable(); //Draggable image (Jquery UI)

  $('.button').click(function(){     //append more image
    var img = $('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">');
    img.draggable();
    $('body').append(img);
  });

}) //End of script

fiddle: https://jsfiddle.net/0jxghvaa/2/

Upvotes: 3

Related Questions