jQuery Active Menu Highlight

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.

View Demo

Highlight Active Menu using jQuery

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.

jquery-active-menu

$(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");
	}
});

CSS for Menu Highlight

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;}

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 12, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?