Pieman
Pieman

Reputation: 13

Prototype insert after

I'm trying to break up an unordered list containing eight items into two lists, each containing four items.

I figured that .inserting closing and opening tags after the fourth list item should cut it:

if(i == 3) {
  $(li).insert({
    after: "</ul><ul>"
  });
}

But Prototype gives me the <ul></ul> in the opposite order.

<ul>
  <li />
  <li />
  <li />
  <li />
<ul></ul>
  <li />
  <li />
  <li />
  <li />
</ul>

Is there a simple answer to this one?

Upvotes: 1

Views: 2756

Answers (4)

JonB
JonB

Reputation: 1320

Use JavaScript's MOD operator to see when you are on the first or 4th row. If you are, create the UL element and then add the LIs to this element.

Something like:

if ( i % 4 == 0 ) {
  currentUl = new Element('ul');
  $('li').appendChild(currentUl);
}

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299068

It doesn't work like that.

Create a new UL, and move the items to that List:

function moveToOtherList(item){
    var myList = item.up('ul');
    var next = myList.next('ul');
    if(!next){
        next = new Element('ul',{style:"margin-top:20px;"});
        myList.insert({after:next});
    }
    next.insert({bottom:item});
}

$$('ul li').each(function(item, index){
    if(index > 3){
        moveToOtherList(item);
    }
});

See this jsfiddle for a working example

Upvotes: 1

Liviu T.
Liviu T.

Reputation: 23664

Here's how I would do it

Html:

<div id="list">
        <ul id="original">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
        </ul>
    </div>

Javascript:

var ul = new Element('ul');
$$('#original li').each(function(li, index) {
    if (index % 3 == 0 && index > 0) {
        $('list').insert({
            bottom: ul
        });
        ul = new Element('ul');
    }
    ul.insert({
        bottom: li
    });

});
$('list').insert({
    bottom: ul
});
$('original').remove();

Look at a live example

Upvotes: 4

jimy
jimy

Reputation: 4908

I dont know in Prototype but in Jquery you can try this http://jsfiddle.net/nxapS/7/

Upvotes: 0

Related Questions