I have the following DOM elements on one horizontal line:
With float
or position:absolute
I can align these elements correctly on one line. However, when the user clicks the swap button, the divs should swap places. I would prefer not to remove the divs from the DOM and adding them again in each other's place. That's because the elements are actually Javascript objects (Google Closure Library components to be more specific) that hold variables and have event handlers attached to them. Is it possible to swap the divs using CSS, without assigning a static width to the divs?
Simplified example:
<div style="position:relative; height:60px;">
<div style="float:left;">Our Team</div>
<div style="float:left;"><button onclick="swap();">swap home/away</button></div>
<div style="float:left;"><select><option>Opponent A</option><option>Opponent B</option></select></div>
</div>
<div style="clear:both;"></div>
When the user clicks the button, the first (our team) and the third (opponent) div should be visually swapped in the browser, preferably without removing the elements from the DOM.
I would prefer not to remove the divs from the DOM and adding them again in each other's place. That's because the elements are actually Javascript objects (Google Closure Library components to be more specific) that hold variables and have event handlers attached to them.
The best solution is to move the elements in the DOM instead. Doing this will preserve existing event handlers, which means your code should still work:
http://jsfiddle.net/thirtydot/LGGW2/
function swap() {
var target1 = document.querySelector('#swapMe > :first-child');
var target2 = document.querySelector('#swapMe > :last-child');
var parent = target1.parentNode;
parent.insertBefore(target1, null);
parent.insertBefore(target2, parent.firstChild);
}
I'm assuming you already have a reference to the elements you want to swap, so you can replace the document.querySelector
lines with whatever is suitable.
After writing this answer, I searched for a more generic "swap" function and found this, which looks good: Swap 2 html elements and preserve event listeners on them