Currently in the process of revamping my portfolio website, and it's still a work in progress. Recently stumbled upon a jquery tutorial that enables a line to animate under anchor elements on hover, which I find quite intriguing. However, I am facing two issues with this feature.
While the line gets the appropriate width and left position on hover, it fails to retain these attributes when not active.
Uncertain about how to update the active element so that the line remains with the link that was clicked. At present, the first anchor tag is always considered the active element, causing the line to animate back to it. I believe a click function is needed to clear the current active element and assign the active class to the new one, but I'm not entirely sure.
The code can be found below, or you can view the issue live on my site Here
Below is the code snippet:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header">
<div class="container">
<nav id="example-one">
<ul>
<li><a class="nav" href="#home">Welcome</a></li>
<li class="current_page_item"><a class="nav" href="#featuredWork">Work</a></li>
<li><a class="nav" href="#caseStudy">Case Study</a></li>
<li><a class="nav" href="#about">About</a></li>
<li><a class="nav" href="#contact">Contact</a></li>
</ul>
</nav>
</div>
</header>
CSS:
#magic-line {
position: absolute;
bottom: 10px;
/*left: 0;
width: 100px; */
height: 3px;
background: #fe4902;
}
JQuery:
//Magic line
$(function() {
/* Add Magic Line markup via JavaScript, because it ain't gonna work without */
$("#example-one").append("<li id='magic-line'></li>");
/* Cache it */
var $magicLine = $("#magic-line");
$magicLine
.width($(".current_page_item").width())
.css("left", $(".current_page_item a").position().left)
.data("origLeft", $magicLine.position().left)
.data("origWidth", $magicLine.width());
$("#example-one li").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$magicLine.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$magicLine.stop().animate({
left: $magicLine.data("origLeft"),
width: $magicLine.data("origWidth")
});
});
});
Appreciate any assistance or guidance given. Thank you in advance.