Last active
December 16, 2015 13:59
-
-
Save zarkone/5445554 to your computer and use it in GitHub Desktop.
Simple page changing mechanizm, Vanilla JS http://vanilla-js.com/
Suitable for small single page applications.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Let's assume that <div> containers with text have class="page" and id=page name + "Text". | |
* And the menu <a> links-switchers have class "menuItem" and id=page name + "Item". | |
* | |
* This script applies class "active" to selected page by observing window.location.href, | |
* with "about" as default page. | |
* | |
* demo: http://audioservice.pro/ | |
* | |
* | |
*/ | |
var pages = document.getElementsByClassName("page"); | |
var menuItems = document.getElementsByClassName("menuItem"); | |
var pagesCount = pages.length; | |
function showPage(page) { | |
var i = pagesCount - 1; | |
var itemFound = false; | |
for(; i >= 0; i--) { | |
if(pages[i].id != page + "Text") { | |
pages[i].classList.remove("active"); | |
} else { | |
pages[i].classList.add("active"); | |
} | |
if(menuItems[i].id != page + "Item") { | |
menuItems[i].classList.remove("active"); | |
} else { | |
menuItems[i].classList.add("active"); | |
itemFound = true; | |
} | |
} | |
if(!itemFound) { | |
showPage("about") ; | |
} | |
} | |
var href; | |
function listenHref() { | |
if (href != window.location.href) { | |
href = window.location.href; | |
var page = href.match("#[A-z]+"); | |
if (page) { | |
page = page[0].slice(1); | |
} | |
showPage(page || "about"); | |
} | |
clearTimeout(timerId); | |
timerId = setTimeout(listenHref, 100); | |
} | |
var timerId = setTimeout(listenHref, 100); | |
showPage("about"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment