Animate shifting highlight in list (with Jquery?)

Viewed 312

I have a list with an active row. When clicking on another row, I want that to be highlighted instead (see snippet). So far so good.

But I also want that shift to be animated. As in: actually move the highlight down or up on the screen.

I assume that this is possible by using a div for the highlight with "position: absolute": Upon clicking on another row, I could calculate the difference in screen position and then shift the "top" attribute of the div accordingly. For the animation I would then use CSS's transition.

But is there a more elegant way to do this?

Thanks in advance!

$(document).ready(function(){

  $('li').on('click', function(){
    $('.highlight').removeClass('highlight');
    $(this).addClass('highlight');
  });

});
.highlight {
  background-color: #d7d7d7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Row 1</li>
  <li class="highlight">Row 2</li>
  <li>Row 3</li>
  <li>Row 4</li>
</ul>

enter image description here

2 Answers
Related