fbpx

SPA using JQuery

Today I’ll show you how to create a SPA (Single Page Application) using JQuery as SPA template is getting more and more popular. Angular 2 has a built-in feature of the SPA template. But some of you want the same feature in jQuery.

What is SPA Templates

SPA (Single Page Application) is the application in which page load’s one time only. Mean if you click on any Link or route page never get a refreshed, DOM Never Re-Load

sammy.js

Because we want to create a SPA (Single Page Application) using JQuery, we will use routing of, the Sammy library is a jQuery library with a storage area of ​​no more than 5.2 KB.
Sammy’s written a script which looks like this:

var app = $ . sammy ( function () { 
this . get ( '# /' , function () { // Write your function here }); 
this . get ( '# About US/' , function () {  // Page Route Function
// Write your function }); 
this . get ( '# contact US /' , function ()  // Page Route Function
{ // function Here }); })
}); app.run();
First of all, we need to initialize the application to use $.sammy and store a copy of the object in the variable app. We can define a “route” directive in Sammy as follows.
this . get ( 'path /' , function () { // ... });

When you call any route this function will be called. In this function, we can write any logic according to our requirements.

Why?

Because each route has a different structure and logic and renders a different page. So we have to define all the rote first, then we will be able to use SPA Template by calling this run() function as app.run().

Example App

Any article or any tutorial is incomplete without an example. So let’s create an example App. It’s a simple blog App with some pages like “Home”, “About US” and “Contact US”. Here we will use static JSON data.

File structure

- index.html <! - layout ->
- app.js <! - Rotuing Logic ->
- css
--- style.css 
- js
--- jquery-1.11.3.min.js
--- sammy.min.js
--- sammy.template.js 
- data
--- blogs.json
- templates <! - the templates pages will be injected into the layout ->
--- article.template
--- article-detail.template
--- about.template

HTML Markup code

We will use the HTML boilerplate to create an HTML code for SPA (Single Page Application) JQuery:

<! DOCTYPE html> 
<html> <head> 
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0" > 
<script src = "js / jquery-1.11.3.min.js " type = " text / javascript " > </ script> 
<script src = " js / sammy.min.js " type = " text / javascript " > </ script> 
<script src = " js / sammy.template.js " type = " text / javascript " > </ script> 
<link rel = "stylesheet" href ="css / style.css" /> <script src = "app.js" > </ script> 
</ head> 
<BODY> < the div Class = "Header-Container" > 
<Header Class = "wrapper , we Clearfix" > 
< - nav> <UL> <Li> <a the href = "#/"> Menu Home </a> </ Li> 
< Li> <a the href = "#/about/"> About </a> </ Li> 
<! - Defining -url - nav According To the route -> </ UL> </ - nav> </ Header> 
</ the div >
<div class = "main-container" > 
<div class = "main wrapper clearfix" > 
<div id = "app" > 
<! - template will be injected here -> </ div> </ div> </ div> 
</ body> </ html> 
  

Define Routes

//app.js ( function ( $ ) {
var app = $ . sammy ( '#app' , function () { this . use ( 'Template' );  
this.Around ( Function ( a callback ) 
{ Var Context = This ; This . load the ( 'Data / Articles.json' ).Then ( Function ( Items ) { 
Context . Items = Items ; }) . Then ( a callback ); }); 
this . get ( '# /' , function ( context ) { 
context . app . swap ( '' ); 
$ . each ( this . items , function ( i , item ) { 
context . render ( 'templates / Blogs.template' , { id : i , item : item }) . appendTo     
( context . $ element ()); }); });
this . get ( '# / about /' , function ( context ) { var str = location . href . toLowerCase (); 
context . app . swap ( ' ); 
context . render ( ' templates / about.template ' , {}) . AppendTo ( Context . $ Element ()); });  
this . get ( '# / Blogs /: id' , function ( context ) { this . item = this . items [ this . params [ 'id' ]]; if (! this . item ) { return this . notFound (); } this . partial ( 'templates / article-detail.template' ); });  
this . before ( '. *' , function () {  
var hash = document . location . hash ; 
        $ ( "nav" ). find ( "a" ). removeClass ( "current" ); 
        $ ( "nav" ). find ( "a [href = '' + hash + '']" ). addClass ( "current" ); });
});
$ ( function () { 
app . run ( '# / About US/' ); }); 
}) ( jQuery );

We initially set up the application within the element ‎#app, where we will add different templates based on the routing path.

this . use ( 'Template' );

We will get the code data from a file articles.jsonusing the load()‎jQuery library’s function (you can also use ‎$.getor ‎$.post), and store the output in the variable context.
Now it’s time to define the directive for an index page using ‎#/‎:

this . get ( '# /' , function ( context ) { 
  context . app . swap ( '' ); 
  $ . each ( this . items , function ( i , item ) { 
    context . render ( 'templates / article.template' , { id : i , item : item }) . appendTo (     
           context . $ element ()); }); });
  

We have data stored in the  context, we will now pass through those data via a loop using the function ‎$.eachand then display in blogs.template. We will also use the function context.app.swap()‎to empty the element in which we will place the contents (‎#app) before the template is rendered.

<article> 
<section> 
<a href="#/blogs/ <%= id %> "> <h2> <% = item . title%> </ h2> </a> 
</ section> </ article>

To display the changeable values we will use the templating Engine using the formula <%= yourdata %>‎
You can also add a link to the details page of each blog using the formula ‎#/blogs/<%= id %>‎.
Clicking on the post link will take us to a template blog-detail.template, where we can show the image of the post and a summary of it … etc.

this . get ( '# / article /: id' , function ( context ) { this . item = this . items [ this . params [ 'id' ]]; if (! this . item ) { return this . notFound (); } this . partial ( 'templates / article-detail.template' ); });  
   
Similarly, we can create a static page called "about" and display it via a template about.template.
this . get ( '# / about /' , function ( context ) { var str = location . href . toLowerCase (); 
    context . app . swap ( ' ); 
    context . render ( ' templates / about.template ' , {}) . AppendTo ( Context . $ Element ()); });  
     
           
We've forgotten the most important step: to configure the app using where you can locate the default route for your app. If you want to open the about page first, you can type:
$ ( function () { 
  app . run ( '# / about /' ); }); 

If you want to perform some operations before calling each routing instruction, you can use the function before()‎. In the following lines, we will make adjustments to the navigation menu ( nav) depending on the current routing path:

this . Before ( '. *' , Function () { Var by hash = Document . Location . by hash ; 
     $ ( " - nav" ). the find ( " of a" ). RemoveClass ( "Current" ); 
     $ ( " - nav" ). the find ( "a [href = '' + hash + '']" ). addClass ( "current" ); });  
This was a very simple blog app, now using this you can create a larger blogger app as per your requirements using SPA (Single Page Application) using JQuery.
References
http://sammyjs.org/download#packages