Question

I need to detach some elements on my page and then reattach them in the same order they were before. The code below does the work of detaching and then reattaching, but gives me a different order.

$("button").toggle(
    function () {        
        p = $('article').not('.1').detach();

        $(this).text("ON");
    },
    function () {
        p.appendTo("section");
        p = null;

        $(this).text("OFF");
    }
);

<button type="button">OFF</button>

<section>
    <article class="2 3">2 3</article>
    <article class="2 3 4">2 3 4</article>
    <article class="1 4 5">1 4 5</article>
    <article class="1 3 5">1 3 5</article>
    <article class="3 4 5">3 4 5</article>
</section>

I can't just use .hide() and .show() because I need to use some CSS classes like article:first-child.

Here is an exemple

Was it helpful?

Solution

It's really not very practical to remember a lot of state about an unknown set of elements' positions in the DOM.

If you're prepared to require Javascript on the site, just use .show() and .hide() and then use jQuery instead of static CSS to assign a class or CSS properties to the first :visible child.

var state = false;

$("button").on('click', function () {
    var $a = $('article');

    state = !state;
    var fn = state ? 'hide' : 'show';
    $a.not('.1')[fn]();  // calls 'hide' or 'show' depending on state

    $a.removeClass('highlight').filter(':visible').first().addClass('highlight');
});

See http://jsfiddle.net/alnitak/tJBjX/

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