Reputation: 841
I have 2 elements when the yellow div is clicked I want to take the red square put it in that yellow div, but to stay on the same position(when the yellow element is clicked the red must not change position) that it was originally. This is just an example of something I do and both elements are position: absolute, so it should stay like this. Is there a way to do that? http://jsfiddle.net/9t6n8dmk/25/
EDIT: äs I said I need both elements to be absolute.
<div class="square" id="square">
</div>
<span class="image" id="image">
</span>
.square{
position:absolute;
height:50px;
width:50px;
left:100px;
top:100px;
background:yellow;
}
.image{
position:absolute;
height:50px;
width:50px;
left:100px;
top:10px;
background: red;
}
let square = document.getElementById("square");
let image = document.getElementById("image");
square.addEventListener("mousedown", function(){
square.appendChild(image);
})
Upvotes: 1
Views: 1214
Reputation: 18393
When you're moving an element into another parent, you have to recalculate the element's position relatively to the new parent:
let square = document.getElementById("square");
let image = document.getElementById("image");
square.addEventListener("mousedown", function() {
if (image.parentElement !== square) {
image.style.top = (image.offsetTop - square.offsetTop) + 'px';
image.style.left = (image.offsetLeft - square.offsetLeft) + 'px';
square.appendChild(image);
}
})
.square {
position: absolute;
height: 50px;
width: 50px;
left: 100px;
top: 100px;
background: yellow;
}
.image {
position: absolute;
height: 50px;
width: 50px;
left: 100px;
top: 10px;
background: red;
}
<div class="square" id="square">
</div>
<span class="image" id="image">
</span>
Upvotes: 2