Skip to content

Instantly share code, notes, and snippets.

@cfjedimaster
Created October 23, 2012 14:01
Show Gist options
  • Save cfjedimaster/3938913 to your computer and use it in GitHub Desktop.
Save cfjedimaster/3938913 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
li.selected { background-color: red; }
</style>
</head>
<body>
<ul id="menu">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li class="selected">Item four</li>
<li>Item five</li>
</ul>
<script>
document.addEventListener("DOMContentLoaded", init, false);
function init() {
//remove the selected class from the li that has it
document.querySelector("li.selected").classList.remove("selected");
//get all the LIs
var menuItems = document.querySelectorAll("ul#menu li");
//How many do we have?
var numItems = menuItems.length;
//Did we have a previous one?
if(window.sessionStorage && window.sessionStorage.getItem("selected")) {
previous = Number(window.sessionStorage.getItem("selected"));
} else {
previous = -1;
}
//Pick one by random
var selected = Math.floor(Math.random()*numItems);
while(selected === previous && numItems > 1) {
selected = Math.floor(Math.random()*numItems);
}
if(window.sessionStorage) window.sessionStorage.setItem("selected", selected);
//And set it
document.querySelector("ul#menu li:nth-child("+(selected+1)+")").classList.add("selected");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment