Skip to content

Instantly share code, notes, and snippets.

@rethna2
Created July 27, 2018 05:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rethna2/9ab51fbd85da3ee88eac9123c2ce74d1 to your computer and use it in GitHub Desktop.
Save rethna2/9ab51fbd85da3ee88eac9123c2ce74d1 to your computer and use it in GitHub Desktop.
A minimal prototype of Single Page Application (SPA)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SPA - demo</title>
<style>
.page {
display: none;
background-color: beige;
min-height: 100vh;
font-size: 2em;
padding: 30px;
}
.page.active {
display: block;
}
header ul {
display: flex;
}
header li {
list-style: none;
margin: 5px 20px;
padding: 5px 10px;
border: 1px solid blue;
cursor: pointer;
}
header li.active {
background-color: burlywood;
}
</style>
</head>
<body>
<header>
<ul>
<li class="active" id="home">Home</li>
<li id="products">Products</li>
<li id="aboutus">About Us</li>
<li id="contactus">Contact Us</li>
</ul>
</header>
<div class="content">
<section class='page home active'> Home Page </section>
<section class='page products'> Products Page </section>
<section class='page contactus'> Contact Us Page </section>
<section class='page aboutus'> About Us Page </section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
<script>
$(function () {
var pageName = window.location.pathname;
pageName = pageName.substr(pageName.lastIndexOf('/') + 1);
getPage(pageName);
$('header li').on("click", function (e) {
history.pushState({}, e.target.id, '/' + e.target.id);
getPage(e.target.id)
})
function getPage(pageName) {
$('header li').removeClass('active');
$('header #' + pageName).addClass('.active');
$('.page').removeClass('active');
$('.content .' + pageName).addClass('active');
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment