Skip to content

Instantly share code, notes, and snippets.

@Toddses
Created March 25, 2015 16:51
Show Gist options
  • Save Toddses/5efdb79bf178a74fab5c to your computer and use it in GitHub Desktop.
Save Toddses/5efdb79bf178a74fab5c to your computer and use it in GitHub Desktop.
jQuery MagicLine Using Transforms
<div class="nav-wrap">
<ul class="group" id="example-one">
<li class="current_page_item"><a href="#">Home</a></li>
<li><a href="#">Buy Tickets</a></li>
<li><a href="#">Group Sales</a></li>
<li><a href="#">Reviews</a></li>
<li><a href="#">The Show</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Photos</a></li>
<li><a href="#">Magic Shop</a></li>
</ul>
</div>
$(document).ready(function() {
var $el, leftPos, newWidth, ratio, origLeft, origRatio,
origWidth = 100,
$mainNav = $("#example-one");
$mainNav.append("<li id='magic-line'></li>");
var $magicLine = $("#magic-line");
origLeft = $(".current_page_item a").position().left;
newWidth = $(".current_page_item").width();
origRatio = (newWidth / $magicLine.width());
$magicLine
.css("transform", "translateX("+origLeft+"px) scaleX("+origRatio+")");
$("li").hover(function() {
$el = $(this).find("> a");
leftPos = $el.position().left;
newWidth = $el.parent().width();
ratio = newWidth / origWidth;
$magicLine
.css("transform", "translateX("+leftPos+"px) scaleX("+ratio+")");
}, function() {
$magicLine
.css("transform", "translateX("+origLeft+"px) scaleX("+origRatio+")");
});
});
body { background-color: rgba(0, 0, 0, 0.6); }
.nav-wrap { margin: 50px auto; background-color: rgba(0,0,0,0.6); border-top: 2px solid white; border-bottom: 2px solid white; }
#example-one { margin: 0 auto; list-style: none; position: relative; width: 960px; }
#example-one li { display: inline-block; }
#example-one li a { color: #bbb; font-size: 14px; display: block; float: left; padding: 6px 10px 4px 10px; text-decoration: none; text-transform: uppercase; }
#example-one li a:hover { color: white; }
#magic-line { position: absolute; bottom: -2px; left: 0; width: 100px; height: 2px; background: #fe4902; transform: translateX(0); transform-origin: left; transition: transform 0.4s; }
@amdad
Copy link

amdad commented Dec 27, 2015

Hi Tod, thanks! Great improvement.

Only thing that buggin me, on page load first position of line is not 'stable'. It is dynamically animate to current item instead of starting on it. So after every click or refresh line just slide in from left. Can this be changed?

You can see the issue when you set current_page_item on other then first item.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment