Membuat tampilan artikel berbentuk daftar atau grid menurut tombol perintah dengan jQuery Masonry sebagai pembangun grid dan santunan JavaScript Cookie sebagai pengingat sesi:
HTML
<nav id="view"> <a href="#" class="grid">Grid</a> <a href="#" class="list">List</a> </nav> <div id="main"> <article> ... </article> <article> ... </article> <article> ... </article> <article> ... </article> </div>
CSS
#view { display:block; width:95%; margin:10px auto; } #view a { display:inline-block; background-color:darkblue; padding:2px 7px; text-decoration:none; color:white; } #view a.active {background-color:darkred} #main { width:98%; margin:10px auto; } article { display:block; background-color:black; font:normal 11px Arial,Sans-Serif; color:white; padding:10px 15px; margin:0 10px 10px; } /* Grid mode */ article.grid { float:left; width:100px; }
jQuery
(function() { var $container = $('#main'), $article = $container.find('article'), $gridNav = $('#view .grid'), $listNav = $('#view .list'); // Functions... function gridMode() { $article.addClass('grid'); $gridNav.addClass('active'); $listNav.removeClass('active'); $container.masonry({ itemSelector: ".grid", isAnimated: true, isFitWidth: true }); createCookie('grid', null, 7000); return false; } function listMode() { $article.removeClass('grid'); $gridNav.removeClass('active'); $listNav.addClass('active'); $container.masonry("destroy"); eraseCookie('grid'); return false; } // Initialize... // If the `grid` cookie reads if (readCookie('grid')) { gridMode(); eraseCookie('grid'); } else { listMode(); } // By user... $listNav.click(listMode); $gridNav.click(gridMode); })();