Skip to content

Instantly share code, notes, and snippets.

@flipsi
Created November 5, 2015 23:36
Show Gist options
  • Save flipsi/ec191b6becb40501bc3e to your computer and use it in GitHub Desktop.
Save flipsi/ec191b6becb40501bc3e to your computer and use it in GitHub Desktop.
JavaScript Variables in URL Fragment (without page reload)
<!DOCTYPE html>
<html>
<head>
<title>Persistent Javascript Values</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" charset="utf-8"></script>
<style type="text/css">
#box {
border-radius: 3px;
width: 90px;
height: 90px;
background-color: black;
}
.box,
button,
p {
margin: 5px;
}
</style>
<script type="text/javascript">
// get a variable from the URL
// this will not need a page reload
// this is a misusage of the fragment (#) which will not work anymore
function getURLVariable(key) {
"use strict";
var hash = window.location.hash;
var things = hash ? hash.substr(1).split(';') : [];
for (var i = 0; i < things.length; i++) {
var thing = things[i].split('=');
if (thing[0] == key)
return decodeURIComponent(thing[1]);
}
return undefined;
}
// save a variable in the URL
// this will not need a page reload
// this is a misusage of the fragment (#) which will not work anymore
function setURLVariable(key, value) {
"use strict";
var regex = RegExp('([#|;])' + key + '=' + '(.+?)(;|$)');
var hash = window.location.hash,
hashNew;
var thing = key + "=" + encodeURIComponent(value);
if (regex.test(hash))
hashNew = hash.replace(regex, "$1" + thing + "$3");
else
hashNew = hash + (hash ? ";" : "") + thing;
window.location.hash = hashNew;
}
// for the little box haha
function setBoxColor(color) {
// document.getElementById('box').style.backgroundColor = color;
$('#box').css('background-color', color);
setURLVariable('boxcolor', color);
}
// restore color from url on page load
$(document).ready(function() {
var color = getURLVariable('boxcolor');
if (color)
setBoxColor(color);
});
</script>
</head>
<body>
<div id="box"></div>
<button onclick="javascript:setBoxColor('green')">Green</button>
<button onclick="javascript:setBoxColor('yellow')">Yellow</button>
<button onclick="javascript:setBoxColor('blue')">Blue</button>
<button onclick="javascript:setBoxColor('red')">Red</button>
<p>Reload the page and the box will keep its color.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment