Jason Axelrod
Jason Axelrod

Reputation: 7805

Move a div with jQuery in a non-destructive manner?

Okay, so I have 3 divs...

<div id="video"></div>
<div id="info"></div>
<div id="chat"></div>

I am using jQuery to move the divs around on a button press.

$('#chat').insertBefore('#video');

There is just an issue I have with this. I believe what this function does is duplicate/clone the chat div, insert it before the video div, then destroy the original chat div. However, this doesn't work well, because as its obvious, the chat div contains a chatroom.

So the way its cloning and destroys loads up a new chat element, which not only takes up a lot of resources, but also forces the user to log back into the chatroom since its a different instance.

Is there a way to move a div in a non-destructive manner? Without cloning and destroying? Some sort of way to physically move the div?

Upvotes: 1

Views: 270

Answers (4)

Jason Axelrod
Jason Axelrod

Reputation: 7805

I solved this issue a different way. Since people confirmed that its not possible to move an iFRAME from one place in the DOM to another without reloading it's contents...

Instead of moving the div in the DOM, I simply left it where it was and applied "position: absolute" to the div I wanted on the top, forcing it to the top.

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

I'm afraid it's not possible to move an IFRAME from one place in the DOM to another place without reloading it's contents.

insertBefore has an issue with dynamic content, specially if you're about to handle
IFRAMES

LIVE DEMO with chat

if you click the SWAP that will insertBefore() the iframe element
you'll notice that the iframe content gets refreshed
the same happens with your chat app (module)

Upvotes: 1

Jay Patel
Jay Patel

Reputation: 647

Document from jQuery site on insertBefore states the following.

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned) and a new set consisting of the inserted element is returned.

Above statement applies to your situation. So your div is not destroyed or cloned.

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

In case if it the element is inserted before many targets, it will be cloned.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

You can try the native insertBefore:

var video = document.getElementById('video'),
    chat  = document.getElementById('chat');

video.parentNode.insertBefore(chat, video);

In a perfect world, the jQuery method should work this way. But if you f.ex have multiple targets and jQuery is being "nice", maybe this way of doing it will shed some light onto your situation...

Upvotes: 1

Related Questions