<body> ... <section id=dashboard class="container" src="pages/dashboard.htm"></section> <section id=about class="container" src="pages/about.htm"></section> <section id=contact class="container" src="pages/contact.htm"></section> <section id=contacts class="container" src="pages/contacts.htm"></section> ... </body>
/* section visibility */ body > section:not(.active) { display:none; }
href="#-"
and.orhref="#-:-"
<form class="form-horizontal" role="form" name="contactDetails"> ... </form> <script> app.handler(function() { //| //| view initialization: //| var $page = $(this); var $firstName = $("[name=firstName]"); var $lastName = $("[name=lastName]"); ... //| //| view presentation: //| return function(param) { var contact = data.contacts[param]; $firstName.val(contact.firstName); $lastName.val(contact.lastName); ... }; }); </script>
app.handler(function() {...})
in the code above initializes our view and registers the data loader function in view.
// Simple single page application framework // Author: andrew @ terrainformatica.com (function($,window){ var pageHandlers = {}; var currentPage; // show the "page" with optional parameter function show(pageName,param) { // invoke page handler var ph = pageHandlers[pageName]; if( ph ) { var $page = $("section#" + pageName); ph.call( $page.length ? $page[0] : null,param ); // call "page" handler } // activate the page $(".nav li.active").removeClass("active"); $(".nav li a[href=#"+pageName+"]").closest("li").addClass("active"); $(document.body).attr("page",pageName) .find("section").removeClass("active") .filter("section#" + pageName).addClass("active"); } // "page" loader function app(pageName,param) { var $page = $(document.body).find("section#" + pageName); var src = $page.attr("src"); if( src && $page.find(">:first-child").length == 0) { $.get(src, "html") // it has src and is empty - load it .done(function(html){ currentPage = pageName; $page.html(html); show(pageName,param); }) .fail(function(){ $page.html("failed to get:" + src); }); } else show(pageName,param); } // register page handler app.handler = function(handler) { var $page = $(document.body).find("section#" + currentPage); pageHandlers[currentPage] = handler.call($page[0]); } function onhashchange() { var hash = location.hash || "#dashboard"; var re = /#([-0-9A-Za-z]+)(\:(.+))?/; var match = re.exec(hash); hash = match[1]; var param = match[3]; app(hash,param); // navigate to the page } $(window).hashchange( onhashchange ); // attach hashchange handler window.app = app; // setup the app as global object $(function(){ $(window).hashchange() }); // initial state setup })(jQuery,this);
app.getData()
and app.postData()
methods - wrappers over $.ajax()
support caching in localStorage and the views switching animation. I leave this functionality to the imagination of readers.Source: https://habr.com/ru/post/200720/