2

I want to move a div from source-parent1 to target-parent2.
only thing is that I can control the offset of the div on parent2.
I have this code I found and tried to alter - added a 10px offset.
1. I can't understand why it fails.
2. I can't seem to figure out why this line is so important, what does it do?

//  $("body").prepend($("#block-2").detach());

var velocity = 1500;

$("button").on("click", function(){
    var pos = $("#parent-block").offset();
    $("body").prepend($("#block-2").detach());
    var move = $("#block-2").css({
        "position": "absolute",
        "z-index": "9999",
        "top": pos.top,
        "left": pos.left
    });
    var block1 = $("#block-1").offset();
    move.animate({
        "top": block1.top + 10,
        "left": block1.left + 10
    }, velocity, function(){
        move.css({"top":"10","left":"10"});
        $("#block-1").prepend(move.detach());
    });
});
#block-1 {
    position: absolute;
    border: 1px solid #f00;
    width: 150px;
    height: 150px;
    right: 0;
    top: 0;
}
#parent-block {
position: absolute;
border: 1px solid #00f;
width: 150px;
height: 150px;
left: 0;
bottom: 0;
}
#block-2 {
position: absolute;
z-index: 9999;
background-color: #0f0;
width: 50px;
height: 50px;
}
button {
position: absolute;
top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block-1"></div>

<div id="parent-block">
    <div id="block-2"></div>
    <button>Move block</button>
</div>

http://jsfiddle.net/shantiS2007/taug59wy/?utm_source=website&utm_medium=embed&utm_campaign=taug59wy

schanti schul
  • 681
  • 3
  • 14

1 Answers1

0

You have to watch out with css position.

Try this one, its working!

var velocity = 1500;

$("button").on("click", function() {
  var pos = $("#parent-block").offset();
  var block2 = $("#block-2").detach();
  $("body").prepend(block2);
  var move = $("#block-2").css({
    "position": "absolute",
    "z-index": "9999",
    "top": pos.top,
    "left": pos.left
  });
  var velocity = "velocity";
  var block1 = $("#block-1").offset();
  move.animate({
    "top": block1.top + 10,
    "left": block1.left + 10
  }, velocity, function() {
    move.css({
      "top": "10",
      "left": "10"
    });
    $("#block-1").prepend(move.detach());
  });
});
#block-1 {
  position: absolute;
  border: 1px solid #f00;
  width: 150px;
  height: 150px;
}

#block-2 {
  position: absolute;
  border: 1px solid #f11;
  width: 150px;
  height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Move block</button>
<div id="block-1">
  <p>Block1</p>
</div>

<div id="parent-block">
  <div id="block-2">
    <p>Block2</p>
  </div>
</div>
Felix Haeberle
  • 1,530
  • 12
  • 19
  • for sure, i changed it in the snippet! I meant the whole css position is taken with care if you want to change elements like this. and would be nice if thats the accepted answer :) – Felix Haeberle Apr 13 '17 at 22:28