I have two divs for different sections of my webpage, a working and a reference section. One is fixed size, the other is variable sized and they are vertically stacked. I am trying to design it so that if you want to work on something in the reference pane, you click a link and it swaps all the data between the two panes. My idea was to do the following:
var working = $("#working_pane").html();
var ref = $("#reference_pane").html();
$("#working_pane").html(ref);
$("#reference_pane").html(working);
The problem with this, is it seems that any javascript referenced inside of these panes (for example, in place editors) get broken upon switching. No javascript errors occur, it’s just that nothing happens, like the javascript ties are broken.
Is there any to move the html without breaking the javascript contained?
When you are working with bits of an HTML document, you should aim to work with the Node objects that are the content as the browser sees it, not HTML strings.
To get HTML the browser has to look at the Nodes and serialise them to a string. Then when you assign that HTML to another part of the document (with
innerHTMLor jQueryhtml(...)), you are telling the browser to destroy all the content that was previously in the element, laboriously parse the HTML string back into a new set of Node objects, and insert these new Nodes into the element.This is slow, wasteful, and loses any aspect of the original Node objects that can’t be expressed in serialised HTML, such as:
So — and this applies whether you’re using jQuery or the plain DOM — don’t throw HTML around! Take the original node objects and insert them into the place you want them (they’ll leave the place they originally were automatically). The references stay intact so scripts will keep working.