Linking to random scenes using Javascript

To have never visit the scene again, you’d want to remove the scene name from the list of scenes to potentially visit. The javascript code for a mouse click action would look like:

	// create an array search function if it doesn't exist (for old versions of IE)
	var myIndexOf = (function (haystack, needle) {
		if(haystack.indexOf) {
			return haystack.indexOf(needle);
		} else {
			for(var i = 0; i < haystack.length; i++) {
				if(haystack[i] == needle) {
					return i;
				}
			}
		}
		return -1;
	});
	
	// setup the scenes the first time this is called
	if(window.remainingSceneNames == null) {
		// two options:
		// #1: use all the scenes automatically
		window.remainingSceneNames = hypeDocument.sceneNames();
		
		// #2: use specific names of scenes (uncomment and name scenes to use)
		//window.remainingSceneNames = ["Scene3", "Scene4", "Scene5"];
		
		// as a starting condition, remove the scene I am currently in
		var currentSceneIndex = myIndexOf(window.remainingSceneNames, hypeDocument.currentSceneName());
		if(currentSceneIndex != -1) {
			window.remainingSceneNames.splice(currentSceneIndex, 1);
		}
	}
	
	// test to see if there are any scenes to go to. If not, don't do anything
	if(window.remainingSceneNames.length <= 0) {
		return;
	}
	
	// choose a random scene
	var randomSceneIndex = Math.floor(Math.random() * window.remainingSceneNames.length);
	var randomSceneName = window.remainingSceneNames[randomSceneIndex];

	// go to that scene
	hypeDocument.showSceneNamed(randomSceneName);
	
	// remove it from the list of available scenes
	window.remainingSceneNames.splice(randomSceneIndex, 1);

Here’s the document showing it off:

ReducingRandomScene.hype.zip (56.7 KB)

Note that the button will still appear clickable. If you wanted a different behavior, you’d want to inspect the window.remainingSceneNames variable and change the button based on that. You might add an On Scene Load javascript that would do something like:

	if(window.remainingSceneNames != null && window.remainingSceneNames.length == 0) {
		var randomSceneButtonElement = document.getElementsByClassName("randomSceneButton")[0];
		hypeDocument.setElementProperty(randomSceneButtonElement, "opacity", .5);
	}

(this relies on your buttons having the class name of randomSceneButton, added in the element inspector)

Hope that helps!

3 Likes