I\'m wondering if it\'s posible to switch positions of two divs with jQuery.
I have two div like this
STUFF ONE
if(div1First){
var div2 = ($('.div2')).detach();
($('.div1')).append(div2);
}else{
var div1 = ($('.div1')).detach();
($('.div2')).append(div1);
}
Fiddle to try it.
var row2content = $('.div2').html(); //Get row 2s content
row2contentnospaces = row2content.replace(' ', ''); //Eliminate whitespace
if(!(row2contentnospaces == '')){ //Check if row2 is empty
var row2 = $('.div2'); //Get row 2
$('.div2').remove(); //remove row2
$('.div1').before(row2); //add row 2 before row 1
}
Here's an example:
http://jsfiddle.net/52xQP/1/
First you want to clone the elements. Then, check a condition if div2 is empty. Then, do the swap:
div1 = $('#div1');
div2 = $('#div2');
tdiv1 = div1.clone();
tdiv2 = div2.clone();
if(!div2.is(':empty')){
div1.replaceWith(tdiv2);
div2.replaceWith(tdiv1);
tdiv1.addClass("replaced");
}
Well ... why are you trying to change the POSITION of the div elements. Does it matter? Why not changing the CONTENT?
var divOneText = $('#div1').html();
var divTwoText = $('#div2').html();
if (divOneText != '' && divTwoText != '') {
$('#div1').html(divTwoText);
$('#div2').html(divOneText);
}
Add trim() if you want to remove whitespace.
I'll throw in my solution
$('.div2:parent').each(function () {
$(this).insertBefore($(this).prev('.div1'));
});
Edit: Doesn't work for whitespace in div2. Here's an updated solution:
$('.div2').each(function () {
if (!$(this).text().match(/^\s*$/)) {
$(this).insertBefore($(this).prev('.div1'));
}
});
I've found elegant jQuery plugin in 4 lines for that. Author Yannick Guinness.
/**
* Swap an element with another one
* @author: Yannick Guinness
* @version: 0.1
*
* @params {Object} element - object that has to be swapped
* @return: {jQuery Object}
*
* @usage:
* $('.one').swap('.two');
*
* @license: MIT
* @date: 2013/07/22
**/
$.fn.swap = function (elem) {
elem = elem.jquery ? elem : $(elem);
return this.each(function () {
$(document.createTextNode('')).insertBefore(this).before(elem.before(this)).remove();
});
};
$('.one').on('click', function () {
alert(true);
});
$('input').click(function () {
$('.one').swap('.two');
});
Run it in fiddle
While @Vigront's answer simple and great (I've upvoted it), it has one serious drawback - on cloning elements loose events, bound to them...
That plugin do not have such the problem. And even fiddle contains click event to demonstrate it.