Harry Harry - 2 months ago 18
Javascript Question

How to use jquery appendTo another div .... and back again

When an item is clicked inside div1, it is appended to the inside of div2. (This works really well!) However I then click the item inside div2 (hoping it will return to div1) but nothing happens. Any ideas very welcome. Is the dom not being updated? Is my selector correct?

<div id="div1">
<div class="items">Audi</div>
<div class="items">Jeep</div>
<div class="items">Mini</div>
</div>

<div id="div2"></div>

$('#div1 .items').click(function(){
$(this).appendTo("#div2");
});


$('#div2 .items').click(function(){
$(this).appendTo("#div1");
});

Answer

Try this.

$(document).ready(function(){
  
 $(function(){
   $("#div1").on("click", ".items", function(){
     $("#div2").append($(this));
   });
  });
  
  $(function(){
   $("#div2").on("click", ".items", function(){
     $("#div1").append($(this));
   });
  });
});
div{
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<div id="div1">
  <h2>Div 1</h2>
  <div class="items">Audi</div>
  <div class="items">Jeep</div>
  <div class="items">Mini</div>
</div>

<div id="div2">
  <h2>Div 2</h2>
</div>

Comments