Author Topic: How Can Elements Generated on the Fly be Made Draggabble?  (Read 220 times)

drayarms

  • Senior Member
  • ****
  • Posts: 135
  • Karma: 1
    • View Profile
How Can Elements Generated on the Fly be Made Draggabble?
« on: June 20, 2012, 03:31:51 PM »
I'm using the script below to generate a set of images on the fly(image names correspond to the names of elements in an array which I call array1). I also give each image an id that is the image's src value, or corresponding array element value.I know you are probably asking yourself why i can't just assign the id names in the HTML image tag.  Reason is, each time i run the program, a different random set of array elements are chosen (array 1 is actually created from a larger array.  the 3 elements making up array1 are randomly selected from that larger array) and their corresponding images need to be appended to the DOM

Code: [Select]

array1 = ['image1', 'image2', 'image3'];//Created on the fly from a larger array

for(i=0; i<array1.length; i++){//Generate an image for each element in array1

$("#image_container").append("<img id = ' "+array1[i]+" ' class = 'images' width = '86px' height = '128px' src =' "+array1[i]+".png'/>");

}





I'm trying to use jQ UI to make all 3 images draggable(I can't use inline HTML5 statements for the same reason why I have to generate the ids on the fly as explained above). But I just can't figure out how to accomplish this, since there is no way of telling before the program is run, which images will be presented.  Here's what I tried which didn't work


example1

Code: [Select]

jQuery.each(array1, function(i,val){//The idea is to iterate the array and get the names of each element which is also the id of corresponding image
 

$( init );
 
function init() { 

  $('#'+val).draggable();
}

});


example2

Code: [Select]
$('.images').mouseover(function() {

   var id = $(this).attr('id');

$( init );
 
function init() { 

  $('#'+id).draggable();
}

});



HTML

Code: [Select]

<img src = 'image1'/>


<img src = 'image2'/>


<img src = 'image3'/>

Smokey PHP

  • Web Developer
  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 618
  • Karma: 9
    • View Profile
Re: How Can Elements Generated on the Fly be Made Draggabble?
« Reply #1 on: June 23, 2012, 01:43:21 PM »
I think I understand what's going on. If so, I would expect the following to work:

Code: [Select]
for(i=0; i<array1.length; i++)
{
    $("<img>").attr({
        id: array1[i]
        ,class: 'images'
        ,width: '86px'
        ,height: '128px'
        ,src: array1[i]
    }).draggable().appendTo($("#image_container"));
}