In Angular 2, how do I animate one element so that it's size and position will match that of another target element? The target element's size and position is not fixed, but can vary at runtime. Attached is a complete example using jQuery. As a bonus, I'm wondering if the animation can be done without using an ElementRef
?
Codepen
See the Pen Animate element on top of another by Matthew Banz (@battmanz) on CodePen.HTML
<section>
<button id="animateBlue">Animate Blue</button>
<button id="randomizeOrange">Randomize Orange</button>
</section>
<section>
<div class="ball" id="ball1"></div>
<div class="ball" id="ball2"></div>
</section>
CSS
body {
margin: 0;
padding: 0;
}
section:first-of-type {
padding: 10px;
text-align: center;
background-color: #ccc;
}
.ball {
border-radius: 50%;
position: absolute;
}
#ball1 {
background-color: blue;
z-index: 5;
}
#ball2 {
background-color: orange;
}
JS
const ball1 = $('#ball1');
const ball2 = $('#ball2');
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomlyAssignOrangePositionSize() {
const radius = getRandomIntInclusive(10, 200);
const top = getRandomIntInclusive(50, 300);
const left = getRandomIntInclusive(10, 900);
ball2.css({
width: radius,
height: radius,
top: top,
left: left
});
}
ball1.css({
width: 50,
height: 50,
top: 100,
left: 50
});
randomlyAssignOrangePositionSize();
$('#randomizeOrange').click(randomlyAssignOrangePositionSize);
$('#animateBlue').click(function() {
ball1.animate({
width: ball2.css('width'),
height: ball2.css('height'),
top: ball2.css('top'),
left: ball2.css('left')
});
});