Skip to content

Instantly share code, notes, and snippets.

@lx4r
Last active December 24, 2015 21:59
Show Gist options
  • Save lx4r/6870021 to your computer and use it in GitHub Desktop.
Save lx4r/6870021 to your computer and use it in GitHub Desktop.
This code snippet echos the next element from a JavaScript array to a html element (e.g. a <div>) starting with a random one. The array can contain text as well as html markup.
/*
1.) Just replace the elements of the array with the ones you want to show.
2.) Replace .next_element with something to switch to the next element (e.g. a button).
3.) Replace .output with the element you want to fill with the elements of the array.
*/
$(document).ready(function() {
var items = Array('1', '2', '3', '4', '<a href="http://example.com">5</a>');
var range = items.length;
var position = Math.floor(Math.random()*range);
$('.output').html(items[position]);
$('.next_element').click(function(){
if (position+1 > range-1) {
position = 0;
} else {
position = position+1;
}
$('.meaning').html(items[position]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment