Last active
December 2, 2020 12:01
-
-
Save Serizao/0e6ff0ec3d3d409859216afa4d4dc336 to your computer and use it in GitHub Desktop.
little JS router
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<button onclick="window.location.hash='/titi'">123</button> | |
<div id="main"> <a class='route' data-href='/toto'>123</a></div> | |
<script> | |
var main = { | |
routeData: function(searchRoute) { | |
data = [{ | |
"title": "Default route", | |
"data": "no route found", | |
"route": "/index" | |
}, { | |
"title": "toto", | |
"data": "dataAdded <a class='route' data-href='/titi'>go titi</a>", | |
"route": "/toto" | |
}, { | |
"title": "titi", | |
"data": "dataAdded <a class='route' data-href='/toto'>go toto</a>", | |
"route": "/titi" | |
}, ] | |
returnElement = data[0] | |
Array.prototype.forEach.call(data, elements => { | |
if (searchRoute == elements.route) { | |
returnElement = elements | |
} | |
}) | |
return returnElement | |
}, | |
router: function() { | |
link = document.getElementsByClassName('route'); | |
window.addEventListener("hashchange", event => { | |
Array.prototype.forEach.call(link, element => { | |
element.removeEventListener("click", event) | |
}) | |
path = event.newURL.split('#')[1] | |
page = this.routeData(path) | |
document.title = page.title | |
document.getElementById('main').innerHTML = page.data | |
link = document.getElementsByClassName('route'); | |
Array.prototype.forEach.call(link, element => { | |
element.addEventListener("click", event => { | |
window.location.hash = event.target.getAttribute('data-href'); | |
}) | |
}) | |
}) | |
} | |
} | |
main.router() | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment