Javacadabra
Javacadabra

Reputation: 5758

Switching Position of two divs in JQuery

When my page loads I have a div that is set to display:block and a second div that is set to display:none.

I've got a toggle switch that I would like to replace the shown div with the hidden div.

Currently, I'm trying to do this, but when I perform the switch I no longer have a reference to the div I've replaced and cannot toggle between them.

I can't position the Div's beside one another in the HTML as the page is a different Layout in Desktop so I'm wondering if it is possible to switch positions and hide the one being replaced?

This is my Fiddle:

http://jsfiddle.net/javacadabra/mdqmto9u/

I'd appreciate any help.

I tried cloning the divs before I switch them but that doesn't work either.

In my fiddle I'm trying to get it so that when you check the box the LEFT div switches position with the RIGHT div and vice versa

Upvotes: 0

Views: 4747

Answers (2)

deebs
deebs

Reputation: 1410

Here is another solution, changing just the content. If you want classes, etc. changed you could adjust your layout to apply css to the innerHTML of your divs. Fiddle: http://jsfiddle.net/e9aa84ry/

$('#check').change(function(){
   var left = $('#div1').html();
   var right = $('#div3').html();
   $('#div1').html(right);
   $('#div3').html(left);
});

Upvotes: 2

j08691
j08691

Reputation: 207861

In my fiddle I'm trying to get it so that when you check the box the LEFT div switches position with the RIGHT div and vice versa

Couldn't you just do this?

$('#check').change(function () {
    if ($(this).is(':checked')) {
        $('#div3').insertBefore($('#div2'));
        $('#div1').insertAfter($('#div2'));
    } else {
        $('#div3').insertAfter($('#div2'));
        $('#div1').insertBefore($('#div2'));
    }
});

jsFiddle example

Upvotes: 6

Related Questions