jacks3
jacks3

Reputation: 49

Active Anchor Navigation

My single page website currently smooth scrolls to anchors with arrow keys. The problem is when you scroll to each section the link thats hovered doesn't follow each section as your over it. It only follows your arrow key commands. How can I change this? This is the current website (http://www.jonasandnicole.com)

CSS

nav.desktop a {
    padding-top:10px;
    padding-bottom:10px;
    text-align:right;
    padding-right:20px;
    color:#CCC;
    -moz-transition: background 0.7s ease;
    -ms-transition: background 0.7s ease;
    -o-transition: background 0.7s ease;
    -webkit-transition: background 0.7s ease;
}
nav.desktop a:hover {
    background-color:rgba(0, 0, 0, 0.5);
    color:#fff;
}
.selected {
    background-color:rgba(0, 0, 0, 0.3);
}

jQuery

<script src="js/jquery.easing.1.3.js"></script>
<script>
$(document).ready(function() {
    $(".desktop a").click(function() {
        $(".desktop a").removeClass("selected");
        $(this).addClass("selected"); 
    });
});
$(function() {
    var lengthDiv = $('.desktop').find('li').length;
    var current = 0;
    $('a').bind('click',function(event){
        var $anchor = $(this);
        current = $anchor.parent().index();

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href#')).offset().top
        }, 1500,'easeInOutExpo');
        /*
        if you don't want to use the easing effects:
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1000);
        */
        event.preventDefault();
    });
    $(document).keydown(function(e){if($(':focus').length <= 0)e.preventDefault()})
    $(document).keyup(function(e){
        var key = e.keyCode;
        if(key == 38 && current > 0){
            $('.desktop').children('li').eq(current - 1).children('a').trigger('click')
        }else if(key == 40 && current < lengthDiv){
            $('.desktop').children('li').eq(current + 1).children('a').trigger('click')
        }
    })
});

</script>

Upvotes: 0

Views: 1720

Answers (1)

grandivory
grandivory

Reputation: 639

What you want to do is set up events when the window reaches certain scroll points. You can do this via $.scroll() or use a library such as waypoints. As an example when using waypoints:

$('#target').waypoint(function(dir)) {
  $('nav <a> elements').removeClass('selected');
  switch(dir) {
    case 'down':
      $('corresponding <a> selector').addClass('selected');
      break;
    case 'up':
      $('previous <a> selector').addClass('selected');
  }
}

This would need to be done for each target element.

Upvotes: 3

Related Questions