User Tools

Site Tools


jquery:swap-2-elements-at-any-distance-keeping-events

jQuery: swap elements at any distance without losing events

This function allows you to swap 2 elements in the DOM, in the same container, regardless of how many other elements are in between, and without losing the events attached to the swapped elements. It works in any direction, left to right, right to left, top to bottom, bottom to top, and mixed. Before getting to this solution I've done lots of experiments and I can state that nothing can beat this in simplicity.

function swapElements($el1, $el2){
	if($el1.index() < $el2.index()){
		$place = $el1.next();
		$el1.insertAfter($el2);
		$el2.insertBefore($place);
	}else{
		$place = $el1.prev();
		$el1.insertBefore($el2);
		$el2.insertAfter($place);
	}
}
jquery/swap-2-elements-at-any-distance-keeping-events.txt · Last modified: 2024/01/16 19:03 by rik