In jQuery è possibile manipolare qualsiasi struttura DOM.
Il seguente plugin trasforma una sequenza di link in un menu mobile dotato di toggle generando una lista non ordinata. Il codice viene eseguito solo sui dispositivi mobile:
(function( $ ) {
$.fn.mobileNavigation = function() {
var isMobile = function() {
var browser = navigator.userAgent;
var uaStr = browser.toLowerCase();
if( uaStr.indexOf( "mobile" ) != -1 ) {
return true;
} else {
return false;
}
};
return this.each(function() {
if( isMobile() ) {
var $nav = $( this );
var opener = $( "<div id="menu-open"/>" );
opener.appendTo( $nav );
var list = $( "<ul class='mobile-navigation'/>" );
var html = "";
$( "a", $nav ).each(function() {
var $a = $( this );
var href = $a.attr( "href" );
var text = $a.text();
html += "<li><a href='" + href + "'>" + text + "</a></li>";
$a.remove();
});
list.html( html ).appendTo( $nav );
$( "#menu-open" ).on( "click", function() {
var $list = $( "ul.mobile-navigation", $nav );
if( $list.is( ":hidden" ) ) {
$list.slideDown( 400 );
} else {
$list.slideUp( 400 );
}
});
} else {
return this;
}
});
};
})( jQuery );
Esempio d'uso:
$(function() {
$( "#navigation" ).mobileNavigation();
});