P. Nick
P. Nick

Reputation: 991

Moving all elements up one and down level

I am displaying a few items in a list that I want to be able to move up and down one level in it's tree when I click a certain button.

<button class="prev">Previous</div>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

<button class="next">Next</div>

When I click on the "next" button, I want all the elements to move down one level, so item 1 would take item 2 place and so on. When I click the "previous" button, the opposite must happen - item 1 would take the place of item 6 and item 6 would take the place of item 5 and so back and so forth.

$(document).ready(() => {
    const images = $("ul > li");

    $(".prev").on("click", () => {
        for(const img of images) {
            $(img).insertBefore($(img).prev());
        }
    });
});

But this is causing problems because it skips every second element sometimes and is not moving them accordingly.

How can I achieve the outcome I'm looking for?

Upvotes: 0

Views: 252

Answers (2)

Turnip
Turnip

Reputation: 36742

If I understand correctly, you only ever need to move one item.

When .next is clicked, take the last item and move it to the first position using .prependTo().

When .prev is clicked, take the first item and move it to the last position using .appendTo().

$(document).ready(() => {
    $(".prev").on("click", () => {
        $("ul > li").first().appendTo("ul");
    });
  
    $(".next").on("click", () => {
        $("ul > li").last().prependTo("ul");
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="prev">Previous</button>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

<button class="next">Next</button>

Upvotes: 1

if you modify your html a bit, then you could do it like this:

$(document).ready(() => {
  $(".move").on("click", () => {
    for (const img of $("ul > li")) {
      if($(this).data("target")=="next")
        $(img).insertAfter($(img).prev());
      else
        $(img).insertBefore($(img).prev());
    }
  });
});

Demo

$(document).ready(() => {
  $(".move").on("click", () => {
    for (const img of $("ul > li")) {
      if($(this).data("target")=="next")
        $(img).insertAfter($(img).prev());
      else
        $(img).insertBefore($(img).prev());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="move" data-target="prev">Previous</button>

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
</ul>

<button class="move" data-target="next">Next</div>

Upvotes: 1

Related Questions