Kobe Bryan Kobe Bryan - 1 month ago 5
jQuery Question

How to swap div using Jquery

Newbie here. Would like to ask for help. How can I swap the 2 divs dynamically. When you flood click the button, it will just swap alternately. I've saw stackoverflow question but it didn't work.

$("button").click(function(){
var v1 = $('.red').val(),
v2 = $('.blue').val();
$('.red').val(v2);
$('.blue').val(v1);
});




$("button").click(function(){
var v1 = $('.red').val(),
v2 = $('.blue').val();
$('.red').val(v2);
$('.blue').val(v1);
});

.red {
color: #fff;
text-align: center;
padding-top: 75px;
box-sizing: border-box;
width: 250px;
height: 250px;
background: red;
position: absolute;
top: 0;
left: 0;
}

.blue {
color: #fff;
text-align: center;
padding-top: 75px;
box-sizing: border-box;
width: 250px;
height: 250px;
background: blue;
position: absolute;
top: 20px;
left: 20px;
}

button {
margin-top: 300px;
clear: both;
display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="red">
I am red!
</div>

<div class="blue">
I am blue!
</div>

<button>Swap box!</button>





Here's my jsfiddle: https://jsfiddle.net/4jbdznpa/

Hope you have a little time to help me for my development.

Answer

I updated your jsfiddle, it uses id instead of class. This will allow you to better 'switch' your divs.

https://jsfiddle.net/4jbdznpa/3/

HTML

<div id="red">
    I am red!
</div>

<div id="blue">
    I am blue!
</div>

<button>Swap box!</button>

Javascript

$("button").click(function(){
    var v1 = $('#red').html(),
        v2 = $('#blue').html();
    $('#red').html(v2);
    $('#blue').html(v1);
    $('#red').prop("id", "TEMP");
    $('#blue').prop("id", "red");
    $('#TEMP').prop("id", "blue");
});

CSS

#red {
    color: #fff;
    text-align: center;
    padding-top: 75px;
    box-sizing: border-box;
    width: 250px;
    height: 250px;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
}

#blue {
    color: #fff;
    text-align: center;
    padding-top: 75px;
    box-sizing: border-box;
    width: 250px;
    height: 250px;
    background: blue;
    position: absolute;
    top: 20px;
    left: 20px;
}

button {
    margin-top: 300px;
    clear: both;
    display: block;
}

Let me know if this is what you were looking for.