4

I'm working with some jquery and found a weird behaviour of jquery .appendTo() function.

Look this code here.

When you click on each item of the first column, the clicked item is appended to the second column.

If you click items 3 and 4, everything will work as expected: They will be appended in the order you clicked them. When you click on item 1, he will be appended correctly too.

The problem is when you click on item 2. This item is inside the item 1.

This item is not appended to the end of the div, he' is appended on top of his old parent!

Look the images:

Step by step

Now, what I was expecting versus what I get:

Expected vs real

If you click again on item 2 he will be appended at the end of the div.

This behaviour have some explanation? It's a bug in fact?

How can I workaround this?

Ps: Jquery 1.10.1

Vinicius Garcia
  • 1,740
  • 4
  • 30
  • 54

1 Answers1

6

When you click on item 2, a "click" event is sent to both item 2 and item 1, because item 2 (when the "click" happens) is a child of item 1. The event bubbles up and the parent gets it too.

Thus, you click on item 2, and the event handler runs. Item 2 is appended to the target. Then the event bubbles to item 1, and the event handler runs again. Now, item 1 is appended after item 2, because (at this point) item 2 is no longer a child of item 1.

Verdict: not a bug.

You can change your handler to prevent that:

$('.item').on('click', function(e){
    // Append clicked item on destiny div
    $(this).appendTo($('.destiny'));
    e.stopPropagation(); // stop the event from bubbling further up
});
Pointy
  • 405,095
  • 59
  • 585
  • 614