This is an answer based on @lotif's answer logic, but bit more generalized
If you append/prepend after/before the elements are actually moved
=> no clonning needed
=> events kept
There are two cases that can happen
- One target has something "
.prev()
ious" => we can put the other target .after()
that.
- One target is the first child of it's
.parent()
=> we can .prepend()
the other target to parent.
The CODE
This code could be done even shorter, but I kept it this way for readability. Note that prestoring parents (if needed) and previous elements is mandatory.
$(function(){
var $one = $("#one");
var $two = $("#two");
var $onePrev = $one.prev();
if( $onePrev.length < 1 ) var $oneParent = $one.parent();
var $twoPrev = $two.prev();
if( $twoPrev.length < 1 ) var $twoParent = $two.parent();
if( $onePrev.length > 0 ) $onePrev.after( $two );
else $oneParent.prepend( $two );
if( $twoPrev.length > 0 ) $twoPrev.after( $one );
else $twoParent.prepend( $one );
});
...feel free to wrap the inner code in a function :)
Example fiddle has extra click events attached to demonstrate event preservation...
Example fiddle: https://jsfiddle.net/ewroodqa/
...will work for various cases - even one such as:
<div>
<div id="one">ONE</div>
</div>
<div>Something in the middle</div>
<div>
<div></div>
<div id="two">TWO</div>
</div>