jQuery: evidenziare la voce di menu corrente nei siti statici

jQuery: evidenziare la voce di menu corrente nei siti statici

Se abbiamo un sito statico è vogliamo fare in modo che le voci del menu di navigazione evidenzino la pagina corrente possiamo ricorrere a jQuery per risparmiarci un lungo e laborioso processo di editing del codice.

Presupponendo l'uso di URL assoluti nei link di navigazione (raccomandato), possiamo definire il seguente plugin jQuery:


(function( $ ) {
	$.fn.currentItem = function( options ) {
		options = $.extend({
			className: "current",
			items: "> li"
		}, options);
		
		return this.each(function() {
		
			var $element = $( this );
			var url = location.href; // URL corrente
			var $items = $element.find( options.items );
			
			$items.each(function() {
				var $item = $( this );
				var $link;
				if( $item.is( "a" ) ) { // è un elemento a?
					$link = $item;
					if( $link.attr( "href" ) == url ) { // l'URL è lo stesso?
						$link.addClass( options.className );
					}	
				} else { // è un elemento li o altro?
					$link.find( "> a:first-child" );
					if( $link.attr( "href" ) == url ) { // l'URL è lo stesso?
						$link.addClass( options.className );
					}	
					
				}
			});
		});
		
	}

})( jQuery );

Esempio d'uso:


$(function() {
	$( "#navigation" ).currentItem();

});

Se i vostri URL sono invece relativi, dovete eseguire un'operazione preliminare con jQuery:


(function( $ ) {
	$.fn.currentItem = function( options ) {
		options = $.extend({
			className: "current",
			items: "> li",
			relative: false
		}, options);
		
		return this.each(function() {
		
			var $element = $( this );
			var url = location.href; // URL corrente
			var $items = $element.find( options.items );
			
			if( options.relative ) {
			
				// trasformiamo gli URL relativi in URL assoluti
			
				var base = "http://" + location.host; // https in caso il protocollo sia quello
				
				$( "a", $element ).each(function() {
					var $a = $( this );
					var href = $a.attr( "href" );
					if( /^\//.test( href ) ) {
						$a.attr( "href", base + href );
					} else {
						$a.attr( "href", base + "/" + href );
					}
				});
			}
			
			$items.each(function() {
				var $item = $( this );
				var $link;
				if( $item.is( "a" ) ) { // è un elemento a?
					$link = $item;
					if( $link.attr( "href" ) == url ) { // l'URL è lo stesso?
						$link.addClass( options.className );
					}	
				} else { // è un elemento li o altro?
					$link.find( "> a:first-child" );
					if( $link.attr( "href" ) == url ) { // l'URL è lo stesso?
						$link.addClass( options.className );
					}	
					
				}
			});
		});
		
	}

})( jQuery );

Quindi:


$(function() {
	$( "#navigation" ).currentItem({
		relative: true
	});

});

Torna su