JSFiddle - React, Tailwind, and code Playground
by abude
HTML
<ul class="clearfix">
<li>test1</li>
<li class="current">test2</li>
<li>test3</li>
<li>test4</li>
<li>test5</li>
<!-- <div id="marker"></div> -->
</ul>
CSS
ul {
position: relative;
}
li {
float: left;
padding: 1em;
list-style-type:none;
text-align: center;
border-right: 1px solid lightgrey;
}
li:last-child {
border: none
}
li:hover, li.active {
color: #5EA15C;
}
#marker {
/* position: absolute; */
/* display:none; */
border:6px solid #004934;
height: 6px;
-webkit-transition:width .3s, left .1s;
-moz-transition:width .3s, left .1s;
-ms-transition:width .3s, left .1s;
-o-transition:width .3s, left .1s;
transition:width .3s, left .1s;
}
JavaScript
var marker = $('#marker'),
current = $('.current');
// Initialize the marker position and the active class
current.addClass('active');
marker.css({
// Place the marker in the middle of the border
bottom: -(marker.height() / 2),
left: current.position().left,
width: current.outerWidth(),
display: "block"
});
$('li').mouseover(function () {
$(this).attr('id','marker');
var self = $(this),
offsetLeft = self.position().left,
// Use the element under the pointer OR the current page item
width = self.outerWidth() || current.outerWidth(),
// Ternary operator, because if using OR when offsetLeft is 0, it is considered a falsy value, thus causing a bug for the first element.
left = offsetLeft == 0 ? 0 : offsetLeft || current.position().left;
// Play with the active class
$('.active').removeClass('active');
self.addClass('active');
marker.stop().animate({
left: left,
width: width,
}, 10);
});
// When the mouse leaves the menu
$('ul').mouseleave(function () {
$(this).removeAttr('id');
// remove all active classes, add active class to the current page item
$('.active').removeClass('active');
current.addClass('active');
// reset the marker to the current page item position and width
marker.stop().animate({
left: current.position().left,
width: current.outerWidth()
}, 10);
});