There are various ways to highlight the active menu item. In this tutorial, we are using jQuery and CSS for adding menu highlighting style dynamically. In a previous tutorial, we have seen how to create scrolling menu using jQuery.
In this example, we have added menu highlight effects on the click event of the menu item. We are adding class selectors to differentiate another menu item from the active one.
The HTML is same as we have seen in previous tutorial jQuery scrolling menu. This code shows jQuery function to highlight active menu on clicking the menu item.
$(document).ready(function (){
$(window).scroll(function(e){
if ($(window).scrollTop() > ($('#scroll-content').height() - $('#scrolling-menu').height())){
var scroll = $('#scroll-content').height() - $('#scrolling-menu').height();
$(window).scrollTop(scroll);
return false;
}
});
$('#scrolling-menu div').click(function() {
var target = $(this).attr('id');
$('html, body').animate({scrollTop: $('#'+target+'-content').offset().top}, 1000);
highlight_active_menu($(this));
});
function highlight_active_menu(obj){
$('.menu-tile').removeClass("active-menu-tile");
$(obj).addClass("active-menu-tile");
}
});
We are using this styles to show the highlighted active menu.
#scrolling-menu{position: fixed;width: 150px;margin-top:10px;}
#scrolling-menu div{line-height:40px;padding:0px 10px;margin-bottom:1px;background: #C7B3B3;color: #F0F0F0;cursor:pointer;}
.active-menu-tile:after{content:"";border-color: transparent transparent transparent #C7B3B3;border-style:solid;border-width:18px;
width:0;height:0;position:absolute;right:-50px;left:154px;}
#scroll-content{border-left:#C7B3B3 4px solid;margin-left:150px;padding-left:60px;color:#E0403A;}
#scroll-content div{margin-bottom: 60px;}