JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
<div class="element">Some text</div>
<div class="element">Some other text</div>
<div class="element">Some more text</div>
</div>
<br>
animate function counter: <input id="count">
CSS
div#container {
border 1px solid;
text-align: center;
position: relative;
}
div.element {
background-color: #f2f2f2;
margin: 2px 0;
height: 30px;
}
JavaScript
$('div#container').prepend($('<div id="pointer">').css({
'border': '1px solid #ffa800',
'height': '28px',
'width': '100%',
'z-index': '100',
'position': 'absolute',
'top': '0',
'right': '0'
}));
function moveElement(el, ypos, dest) {
if (el.moving) {
clearTimeout(el.moving);
}
if (ypos < dest) ypos++;
if (ypos > dest) ypos--;
el.style.top = ypos + 'px';
el.moving = setTimeout(function() {
moveElement(el, ypos, dest);
}, 5);
}
var counter = 0;
function animate(el, dir, step) {
$("#count").val(counter);
counter++;
var ypos = parseInt(el.style.top),
step_count = 2,
dest = step;
if (ypos === dest) {
if (dir === 'down') {
dest = dest + step;
}
if (dir === 'up') {
dest = dest - step;
}
}
moveElement(el, ypos, dest);
if (ypos === 0) {
dir = 'down';
}
if (ypos === (step * step_count)) {
dir = 'up';
}
el.timer = setTimeout(function() {
animate(el, dir, step);
}, 2000);
}
var pointer = document.getElementById('pointer'),
step = 32;
$('div.element').each(function(index, element) {
$(this).on({
mouseenter: function() {
clearTimeout(pointer.timer);
clearTimeout(pointer.moving);
pointer.style.top = index * step + 'px';
},
mouseout: function() {
setTimeout(function() {
animate(pointer, 'down', step);
}, 500);
}
});
});
animate(pointer, 'down', step);