giocarmine
giocarmine

Reputation: 580

JQuery-ui: element loses its "draggability"

I'm developing a sort of web-based map editor and I'm using JQuery and JQuery-ui. I use the latter principally to make the objects draggable. Objects are created and inserted in the page in a default position as the user clicks on a button. When the object is created i make it draggable.

What happens is that if I create 2 or more objects that overlaps i can drag only the one that is on the top, the others loses their draggability. If I add those objects and I move them somewhere and after i make them overlap there is no probleb, I still can drag them where i want. The problems happens only when the objects overlap when they are created.

Here is the code i wrote.

<html>
    <head>
<script type="text/javascript" src="wz_jsgraphics.js"></script>
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.custom.min.js"></script>

<script type="text/javascript"> 
     var lastNodeId;

     $(function() {
         lastNodeId = 0;
         $("#nodeButton").click( addNode ); 
     });


    function addNode() {
        var id = "node" + lastNodeId;

        $("#drawArea").append("<div id=\"" + id + "\" class='node'></div>");

        var jg = new jsGraphics(id);
        jg.setColor("#000000"); 
        jg.drawImage("pc_icon.png", 50, 50, 50, 50);
        jg.paint();

        var idImg = "img" + lastNodeId;
        $("#" + id + " img").attr("id", idImg);

        lastNodeId++;
        $("#" + idImg).draggable();

}

</script>
</head>

<body>
    <button type="button" id="nodeButton">Aggiungi Nodo</button>
    <div id="drawArea"> </div>
</body>
</html>

I use JSGraphics just to draw an icon on the page, it can be found at http://www.walterzorn.de/en/jsgraphics/jsgraphics_e.htm. I really hope that someone can help me understand what happens and what I'm doing wrong! :)

Update

I've tried to add the next object in a different place. I found that if the distance to the previous added object is at least 17px, the bottom one doesn't lose its draggability. No matter if I modify the x or y parameters, it has just to be at least 17px away.

Upvotes: 0

Views: 195

Answers (1)

Try with replacing your following code:

$("#" + id + " img").attr("id", idImg);

lastNodeId++;
$("#" + idImg).draggable();

for this one:

$("#" + id + " img").attr("id", idImg).draggable();
lastNodeId++;

as it could be new id set is not updated for the dom so quickly that jQuery grabs it.

Update:
If you do:

lastNodeId++;
console.log('im len: '+$("#" + idImg).length);
$("#" + idImg).draggable();

what does it print in console? It could be the image is not already created, see if jqGraphics has a callback for when an image is created.

Upvotes: 1

Related Questions