Question

I want to select two elements and when I click the button element I want them to swap place, how would I do that? I've searched and looked for similar answers, but most of them only swap the element up or down.

I'm thinking something like:

$('button').click(function(){
   $('#item 1 .selected-item').removeClass('.selected-item').appendTo('#item2');
   $('#item 2 .selected-item').removeClass('selected-item').appendTo('#item1');
});

But I don't know how to start, it should look something like this:

http://jsfiddle.net/tLNAh/1/ (my fiddle)

Was it helpful?

Solution 2

With your markup do this:

$("button").on("click", function() {
    $('.selected').insertBefore($('ul:eq(1) li:first'));
});

Demo

Or you can update to this:

$("button").on("click", function() {
   if($('.selected').closest('ul').index() < $('.selected').closest('ul').siblings('ul').index()){
      $('.selected').insertBefore($('ul:eq(1) li:first'));
   }else{
      $('.selected').insertBefore($('ul:eq(0) li:first'));
   }
});

Updated fiddle

OTHER TIPS

try this. http://jsfiddle.net/tLNAh/3/

$("button").on("click", function() {
    $first = $(".selected:eq(0)");
    $second = $(".selected:eq(1)");
    var tempText = $first.text();
    $first.text($second.text());
    $second.text(tempText);
    $("#instructionText").text("Instructions: choose an item");
});

Chk this : fiddle link

Provide id to your ul :

<ul id="item1">
<ul id ="item2">

And try this :

$("button").on("click", function() {
   $("#instructionText").text("Instructions: choose an item");    
   $('#item1 .selected').removeClass('selected').remove().appendTo('#item2');
   $('#item2 .selected').removeClass('selected').remove().appendTo('#item1');
});

$("body").on("click","li", function(e) {
   $(this).toggleClass("selected");        
   $("#instructionText").text("Instructions: choose the item to change place with");
});

You have to get index of list elemet and use this: http://jsfiddle.net/faceleg/FJt9X/2/

var swapElements = function(siblings, subjectIndex, objectIndex) {
    // Get subject jQuery
    var subject = $(siblings.get(subjectIndex));
    // Get object element
    var object = siblings.get(objectIndex);
    // Insert subject after object
    subject.insertAfter(object);
}
$(function() {
    swapElements($('li'), 0, 1);
});

Try this:

function swapItems(first, second) {
    var sibling = first.next();
    if (sibling.length) {
        first.insertBefore(second);
        second.insertBefore(sibling);
    } else {
        sibling = first.prev();
        if (sibling.length) {
            first.insertBefore(second);
            second.insertAfter(sibling);
        } else {
            var parent = firstItem.parent();
            first.insertBefore(second);
            second.appendTo(parent);
        }
    }
}

Updated fiddle


Edit: I updated the fiddle, now you have to click the button to swap items.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top