Is flipping a coin really random?

Week 8


a nice reference card
Animating a Div
This first example we started working on in class last week, but here it is in the flesh. This function is called when the body loads, and then is re-called with the line - setTimeout("iterate()",20); so when the script ends it waits for 20 iterations, then calls itself again. A script that calls itself is called "recursion".

woosh!

<!doctype html>
<html>
<head>
<style type="text/css">
	#animateddiv{
		margin-left: auto;
		margin-right: auto;
		width: 20px; 
		height: 20px; 
		border: 1px blue solid;
		background-color:green;
		color: white;
		text-align:center; 
	}
</style>
<script type="text/javascript">
	var divwidth = 20; 
	function iterate(){
		divwidth ++; 
		if (divwidth > 300){
			divwidth = 20;
		} 
		document.getElementById('animateddiv').style.width = divwidth + "px"; 
		setTimeout("iterate()",20); 
	}  
</script>
</head>
<body onload="iterate()">
<div id="animateddiv"> Woosh!</div>
</body>
</html>

Okay, this was fun, but the woosh "jumps" back to 20 px - what if we want it to animate back to a closed position? We need to determine which way the animation is going, then either add or subtract based on the direction. Finally we need to check the size of the div and change the direction if it is the max or min size.

Replace the javascript above with this code to fully animate the div. The Boolean "dir" is used as an indicator of which direction the div is moving.

var dir = false;
var divwidth = 20; 
function iterate(){
	if (dir == false){
		divwidth ++; 
	} 
	else{
		divwidth --; 
	}

	if (divwidth > 300){
		dir = true; 
	}  
	if (divwidth < 0 ){
		dir = false; 
	} 
	document.getElementById('animateddiv').style.width = divwidth + "px"; 
	setTimeout("iterate()",1); 
}  
I used a similar script to change the background color in last week's class. Try adding this line...

document.getElementById('animateddiv').style.background = "rgb("+ divwidth + ", 15, 15)" ;

RANDOM!

keeping with our "woosh" example, what if the color was randomized each time it expands? Random in javascript is a little trickier than in Processing. Random always returns a value between 0 and 1, and so we will need to do some math to make that number a value between 0 and 255. This is the code to get a random number. Random is actually a property of the Math object, so we need to reference Math first, then random

var x = Math.random();

in this case x would be a number like 0.8261494619459748
To make x a number between 0 and 255 we need to multiply the number by 256, then round down. We use the "floor" property to do the rounding and give us a whole number.

var x = Math.floor(Math.random()*256);

Challenge: Make three variables called red green and blue. When the div is at it's smallest size randomly change these variables to a value between 0 and 256. (This is the tricky part) Apply these variable to the background color of the div.

Better Buttons

Last week we used the input tag to make buttons, and this is sweet because there are other types of input. But those buttons look boooooring. Fortunately there's the new button tag. This is boss because you can put anything, even images, in a button tag AND also apply your own CSS to it.
	<style type="text/css">
		#button{
			background-color: blue;
			border: 2px solid black;
			color: white;
			padding: 15px 32px;
			text-align: center;
			text-decoration: none;
			font-size: 16px;
			margin: 4px 2px;
			cursor: pointer;
			border-radius: 12px; 
		}
	</style>
	<script type="text/javascript">		   
		function swapColor(){ 
			var ran = Math.floor(Math.random()*256);
			document.getElementById("button").style.background = "rgb("+ ran + ", 15, 15)" ;
			console.log(ran);
		}
	</script>
	<button onclick="swapColor()" id="button" >Button</button>
	

Arrays and Loops

An array is nerdy programmer lingo for "list". you can have an array of text or numbers. In the following example we create an array of Snow White's Dwarves. When the button is pressed it uses a "for" loop (this should be familiar from the Code academy) to go through every instance of the list and compare it to the value of our input field. If the inputed dwarf is in the list it removes it, so next time the array is one smaller. Notice that we are going from 0 to ONE LESS than the length of the array - this is because computers count arrays starting from 0 not 1. Confusing? Yes, yes it is.
Finally, it prints out a list of the Dwarves to the console.

	<!doctype html>
	<head>
	<script type="text/javascript">
	var dlist=new Array("Sneezy","Sleepy","Dopey", "Doc","Happy","Bashful","Grumpy");     
	function buttonInput4(){
	var input =  document.getElementById('textbox').value; 
	var i; 
	for (i=0;i<=dlist.length -1 ;i++){
	if (dlist[i] == input){
	dlist.splice(i,1);
	  } 
	}
	console.log(dlist);  
	}
	</script>
	</head>
	<body>
	<form>
	Type one of Snow White's Dwarves and press the button.<p>
	<input type="text" value ="" id="textbox" size="20" <br> 
	<input type="button" value= "GO!" onclick="buttonInput4()">
	</form> 
	</body>
	</html>

Of course we need to keep working on this script. We need to reward the player for correctly guessing a dwarf and punish them for getting it wrong! Let's set a boolean that we set to false every time the button is pressed. If the player is successful we'll set the boolean to true, otherwise it will remain false. This way we can check the boolean, and if it is false we can "alert" the player.
 
	<!doctype html>
	<head>
	<script type="text/javascript">
	var dlist=new Array("Sneezy","Sleepy","Dopey", "Doc","Happy","Bashful","Grumpy");     

	function buttonInput4(){
	var input =  document.getElementById('textbox').value; 
	checkD = false; 
	var i=0;
	for (i=0;i<=dlist.length -1 ;i++){
	if (dlist[i] == input){
	checkD = true;
	dlist.splice(i,1);
	} 
	}
		if (checkD === false){
		alert("you idiot that is not one of them. Start OVER!"); 
	}
	console.log(dlist);  
	}

	</script>
	</head>
	<body>
	<form>
	Type one of Snow White's Dwarves and press the button.<p>
	<input type="text" value ="" id="textbox" size="20" <br> 
	<input type="button" value= "GO!" onclick="buttonInput4()">
	</form> 
	</body>
	</html>

Now put in a reward! Change the code so that if the person names all seven Dwarves without making a mistake they get to go to a new site. Hint: the javascript code for going to a new page is: window.open("your url here");


Images and Sending Info to Routines

<!doctype html>
<head>
	<script type="text/javascript">
		function image1(){
			document.getElementById("image").width= 200; 
			document.getElementById("image").src="images/nailsm.jpg";
		} 

		function image2(){
			document.getElementById("image").width= 200; 
			document.getElementById("image").src="images/thumbdrive.jpg";
		} 

		function image3(){
			document.getElementById("image").width= 200; 
			document.getElementById("image").src="images/cheeseplate1.jpg";
		} 

	</script>
	<style>
		.redbox{
			border:2px solid red; 
			width: 320px; 
			height: 40px; 
			margin-left: auto; 
			margin-right: auto
		} 

		.blackbox{
			float: left; 
			border:2px solid black; 
			width: 80px; 
			height: 15px; 
			margin: 10px;
		}
		#imagearea{
			text-align: center; 
			margin-left: auto; 
			margin-right: auto;
			border:2px solid green; 
			width: 400px; 
			height: 200px; 
			margin-bottom: 30px; 
		}
	</style>
</head>
<body>
	<div id="imagearea"> <img src="images/nailsm.jpg" alt="" vspace="8" hspace="5" id="image"> </div> 
	<div class="redbox"> 
		<div class="blackbox" onMouseover="image1()" > </div>
		<div class="blackbox" onMouseover="image2()" > </div>
		<div class="blackbox" onMouseover="image3()" > </div>
	</div>
</body>
</html> 

We have done this with onMouseover, but it would also work with onClick like the earlier examples. Also, the divs we are rolling over can have thumbnails of the image in them of course. This method works fine if there are only a few images, but if there are a lot it can become a lot of repeated code. Any time you are writing the same thing over and over, there's probably a better way. The answer here is to pass information to the function, so that we are giving the function custom information on each click. In this case we are sending the width and the name of the image, and we only need to use one function to piece them all together.

		function image3(size,im){
		document.getElementById("image").width= size; 
		document.getElementById("image").src=im;
	} 

	////////

	<div class="blackbox" onMouseover="image3(100, 'images/nailsm.jpg')" > </div>
	<div class="blackbox" onMouseover="image3(150, 'images/thumbdrive.jpg')" > </div>
	<div class="blackbox" onMouseover="image3(200, 'images/cheeseplate1.jpg')" > </div>
Challenge:
1. Make the rest of the screen go dark (cool).
2. animate the div opening to reveal the image.


DATE & TIME

getting the date and time.

		<script type="text/javascript">

		function show(){
		var newtime=new Date();
		document.getElementById("clockid").innerHTML = newtime; 
		setTimeout("show()",1000);
	}
	</script>

	////////

	<body onLoad="show()">	
	<div id="clockid"> </div>

What if you only want the time and not all that other stuff. Here's a hint - you need to extract the hours minutes and second into separate variables. Then recombine it together again.

	
		var hours=newtime.getHours();
		var minutes=newtime.getMinutes();
		var seconds=newtime.getSeconds();
	
Location! There'a a few nice thing going on in this code.
<!DOCTYPE html>
<html>
<head>
	<style>
		#b1{
			font-size: 20px; 
			padding: 15px;
		}
	</style>

</head>
<body>
	<p>Click the button to get your coordinates.</p>
	<button onclick="getLocation()" id="b1">Try It</button>
	<p id="demo">no location yet</p>
</body>

<script>
	var myVar = setInterval(getLocation, 3000);
	var x = document.getElementById("demo");
	function getLocation() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(showPosition);
		} else { 
			x.innerHTML = "Geolocation is not supported by this browser.";
		}
	}
	function showPosition(position) {
		x.innerHTML = "Latitude: " + position.coords.latitude + 
		"<br>Longitude: " + position.coords.longitude;	
	}
</script>

</html>

LAB

Using Javascript techniques we covered in the last two weeks make a website that is a "non-traditional" clock. Your site may not be used to tell time in a traditional manner. Push the boundaries of how a clock operates. Have fun and make something cool looking. Post your page and link to it from your index page. It must use Javascript - challenge yourself!


Work on your location projects