Created
October 23, 2012 14:01
-
-
Save cfjedimaster/3938913 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
<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