Home > Software design >  How can i continuesly using appenTo() when i click a button?
How can i continuesly using appenTo() when i click a button?

Time:12-03

im trying to reverse div with Jquery which when i click a button the divs will reverse and switch place

<div >
  <div >
      <div >
           <h4>Samsudin</h4>
      </div>
    
       <div >
    
       </div>
   </div>
    
   <div >
      <div >
          <h4>Joko</h4>
      </div>
    
      <div >
    
      </div>
   </div>

</div>
<button  id="score_kiri"><h1>SCORE</h1></button>

whenever this button clicked the div p1b will move to div player1-a and so do div p1a will move to div player1-b.

Here's my jquery code that the divs only move once and dont move again when i click again.

$('#score_kiri').click(function() {
        $('#player_kiri').val(i  );
        $('.p1a').appendTo('.player1-b');
        $('.1a').appendTo('.player1-b');
        $('.p1b').appendTo('.player1-a');
        $('.1b').appendTo('.player1-a');
        
        $('.p1a').append('.player1-b');
        $('.1a').append('.player1-b');
        $('.p1b').append('.player1-a');
        $('.1b').append('.player1-a');
    });

CodePudding user response:

Does this works for you?

$(document).ready(function() {
  $('#score_kiri').click(function() {
    $('.player1-a .pemain').appendTo('.player1-b');
    $('.player1-b .pemain').appendTo('.player1-a');
  });
});

CodePudding user response:

Your issue is that you have hard-coded the elements to move, rather than use relative positions. Effectively saying "make it exactly like this" rather than "move the first one to the end" (which I believe is what you're trying to do).

You can select the first one various ways, here's one:

$(".player1 > div").first()

Using .appendTo(".player1") with this will move the element to the end - so by always moving the first to the end you get your "continuously appendTo". If you have 3, then first will move to the end each time.

This is slightly different from "switching places" but has the same effect when only 2.

Updated snippet:

$("#btn").click(() =>
  $(".player1 > div").first().appendTo(".player1")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <h4>p1a Samsudin</h4>
    </div>
    <div >1a
    </div>
  </div>

  <div >
    <div >
      <h4>p1b Joko</h4>
    </div>
    <div >
      1b
    </div>
  </div>
</div>
<button id=btn>
click me
</button>

  • Related