javascript intro

$(“#main”).append(“[name]”);

var email = "cameron@email.com";
var newEmail = email.replace("email.com","gmail.com");
console.log(email);
console.log(newEmail);

var formattedName = HTMLheaderName.replace("%data%", name);

$("#header").append(formattedName)

The prepend() method inserts specified content at the beginning of the selected elements.

var formattedName = HTMLheaderName.replace("%data%", name);
var role = "web developer";
var formattedRole = HTMLheaderRole.replace("%data%", role);

$("#header").prepend(formattedName);
$("#header").prepend(formattedRole);

var s = “audacity”;
s = s[1].toUpperCase() + s.slice(2);

var sampleArray = [0,0,7];

var incrementLastArrayElement = function(_array) {
    var newArray = [];
    newArray = _array.slice(0);
    var lastNumber = newArray.pop();
    newArray.push(lastNumber + 1);
    return newArray;
};
console.log(incrementLastArrayElement(sampleArray));

object

var bio = {
  "name":"john doe",
  "role":"web developer",
  "contacts":{
    "mobile":"080-1234-5678",
    "email": "john@example.com",
    "github":"hohndoe",
    "twitter": "@johndoe",
    "location": "San Francisco"
  },
  "welcomeMessage": "testtesttest",
  "skills": [
    "awsomenss", "delivering things", "cryogenic sleep", "saving universe"
  ],
  "bioPic": "images/fry.jpg"
}

object model

var work = {};
  work.position = "web development";
  work.employer = "more than 1000";
  work.years = "0";
  work.city = "yurakucho";

var education = {};
  education["name"] = "nova southern university"
  education["years"] = "2005-2013"
  education["city"] =  "fort lauderdale, fl, us"

$("#main").append(work.position);
$("#main").append(education.name);

迷路

左上を迷路のスタート地点、右下を迷路のゴール地点とし、0と1の配列で道と壁を作成しています。迷路作成のアルゴリズムは、棒倒し法で記載しています。考えた人は天才ですね。。

棒倒し法 
1.一つとびに壁を作る 1れつ目の棒を上下左右のどちらかに倒す
2.2列目以降の棒を左以外のどれかに倒す
00010
11010
00000
01011
01000

どの位置を0から1に変更するかは、以下のように記載します。
var points = [
 [0, -1],
 [0, 1],
 [1, 0],
 [-1, 0],
];

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>MAZE</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="styles.css">
	<style>
	body {
		font-family: "Century Gothic";
		font-size: 16px;
	}
	#container {
		text-align: center;
		margin: 20px auto;
	}
	#mycanvas {
		background: #AAEDFF;
	}
	.btn {
		margin: 3px auto;
		width: 200px;
		padding: 5px;
		background: #00AAFF;
		color: #ffffff;
		border-radius:3px;
		cursor: pointer;
	}
	.btn:hover{
		opacity: 0.8;
	}

	</style>
</head>
<body>
	<div id="container">
		<canvas width="100" height="100" id="mycanvas">
			Canvasに対応したブラウザを用意してください。
		</canvas>
		<div id="reset" class="btn">RESET</div>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<script>
	(function(){

		var Maze = function(col, row){
			this.map = [];
			this.col = col;
			this.row = row;
			this.startX = 0;
			this.startY = 0;
			this.goalX =col - 1;
			this.goalY =row - 1;
			this.points = [
					[0, -1],
					[0, 1],
					[1, 0],
					[-1, 0],
				];


			this.rand = function(n) {
             return Math.floor(Math.random() * (n + 1));
            };
            this.init = function() {
                for (var x = 0; x < col; x++) {
                    this.map&#91;x&#93; = &#91;&#93;;
                    for (var y = 0; y < row; y++) {
                        this.map&#91;x&#93;&#91;y&#93; = 0;
                    }
                }
					for (var x = 1; x < col; x += 2) {
                    for (var y = 1; y < row; y += 2) {
                        this.map&#91;x&#93;&#91;y&#93; = 1;
                    }
                }
                for (var x = 1; x < col; x += 2) {
                    for (var y = 1; y < row; y += 2) {
                        do {
                            if (x === 1) {
                                // 上下左右に倒す
                                var r = this.points&#91;this.rand(3)&#93;;
                            } else {
                                // 左以外に倒す
                                var r = this.points&#91;this.rand(2)&#93;;
                            }
                        } while (this.map&#91;x + r&#91;0&#93;&#93;&#91;y + r&#91;1&#93;&#93; === 1);
                        this.map&#91;x + r&#91;0&#93;&#93;&#91;y + r&#91;1&#93;&#93; = 1;
                    }
                }
            };
				this.draw = function() {
                var view = new View();
                view.draw(this);
            };
        };

		var View = function(){
			this.wallSize = 10;
			this.wallColor = '#3261AB';
			this.routeColor = '#ff0088';

			this.canvas = document.getElementById('mycanvas');
			if (!this.canvas || !this.canvas.getContext){
				return false;
			}
			this.ctx = this.canvas.getContext('2d');
			this.draw = function(maze){

				this.canvas.width = (maze.col + 2) * this.wallSize;
				this.canvas.height = (maze.row + 2) * this.wallSize;

				// 上下の壁
				for (var x = 0; x < maze.col + 2; x++) {
		            this.drawWall(x, 0);
		            this.drawWall(x, maze.row + 1);
		        }
				// 左右の壁
				for (var y = 0; y < maze.row + 2; y++) {
		            this.drawWall(0, y);
		            this.drawWall(maze.col + 1, y);
		        }

		        // 迷路の内部
		        for (var x = 0; x < maze.col; x++){
		        	for(var y = 0; y < maze.row; y++){
		        		if(maze.map&#91;x&#93;&#91;y&#93; === 1){
		        			this.drawWall(x + 1, y + 1);
		        		}
		        		if ((x === maze.startX && y === maze.startY) || (x === maze.goalX && y === maze.goalY))
		        		{
		        			this.drawRoute(x + 1, y + 1);
		        		}
		        	}
		        }
			};

				this.drawWall = function(x, y) {
		            this.ctx.fillStyle = this.wallColor;
		            this.drawRect(x, y);
		        };
		        this.drawRoute = function(x, y) {
		            this.ctx.fillStyle = this.routeColor;
		            this.drawRect(x, y);
		        };

		        this.drawRect = function(x, y){
		        		this.ctx.fillRect(
		        	 	x * this.wallSize,
		                y * this.wallSize,
		                this.wallSize,
		                this.wallSize);
		        };

		};

		function reset(){
			var maze = new Maze(13, 13);
			maze.init();
			maze.draw();
		}

		reset();

		document.getElementById('reset').addEventListener('click', function(){
			reset();
		});
		// // 迷路のデータを配列で用意

		// // 0と1の配列で、1を壁と表現する ※奇数でないと道ができない
		// // canvasで描画

		// // 棒倒し法 
		// // 一つとびに壁を作る 1れつ目の棒を上下左右のどちらかに倒す
		// // 2列目以降の棒を左以外のどれかに倒す

		// // 00010
		// // 11010
		// // 00000
		// // 01011
		// // 01000


		// var map = &#91;&#93;;
		// // map&#91;0&#93; = &#91;0, 0, 0&#93;;
		// // map&#91;1&#93; = &#91;0, 1, 1&#93;;
		// // map&#91;2&#93; = &#91;0, 0, 0&#93;;

		// var col = 13; // 奇数
		// var row = 13; // 奇数

		// for (var x = 0; x < col; x++){
		// 	map&#91;x&#93; = &#91;&#93;;
		// 	for (var y = 0; y < row; y++){
		// 		map&#91;x&#93;&#91;y&#93; = 0;
		// 	}
		// }

		// for (var x = 1; x < col; x += 2){
		// 	for(var y = 1; y < row; y += 2){
		// 		map&#91;x&#93;&#91;y&#93; = 1;
		// 	}
		// }

		// var points = &#91;
		// 	&#91;0, -1&#93;,
		// 	&#91;0, 1&#93;,
		// 	&#91;1, 0&#93;,
		// 	&#91;-1, 0&#93;,
		// &#93;;



		// function rand(n){
		// 	return Math.floor(Math.random() * (n + 1));
		// }

		// for (var x = 1; x < col; x += 2){
		// 	for(var y = 1; y < row; y += 2){
		// 		map&#91;x&#93;&#91;y&#93; = 1;
		// 		do {
		// 			if (x === 1){
		// 				var r = points&#91;rand(3)&#93;;
		// 			} else {
		// 				var r = points&#91;rand(2)&#93;;
		// 			}
		// 		} while (map&#91;x + r&#91;0&#93;&#93;&#91;y + r&#91;1&#93;&#93; === 1);
		// 		map&#91;x + r&#91;0&#93;&#93;&#91;y + r&#91;1&#93;&#93; = 1;
		// 	}
		// }



		// var startX = 0;
		// var startY = 0;
		// var goalX =col - 1;
		// var goalY =row - 1;

		// var wallSize = 10;
		// var wallColor = '#3261AB';
		// var routeColor = '#ff0088';

		// var canvas = document.getElementById('mycanvas');
		// if (!canvas || !canvas.getContext){
		// 	return false;
		// }
		// var ctx = canvas.getContext('2d');

		// canvas.width = (col + 2) * wallSize;
		// canvas.height = (row + 2) * wallSize;

		// // 上下の壁
		// for (var x = 0; x < col + 2; x++) {
  //           drawWall(x, 0);
  //           drawWall(x, row + 1);
  //       }
		// // 左右の壁
		// for (var y = 0; y < row + 2; y++) {
  //           drawWall(0, y);
  //           drawWall(col + 1, y);
  //       }

  //       // 迷路の内部
  //       for (var x = 0; x < col; x++){
  //       	for(var y = 0; y < row; y++){
  //       		if(map&#91;x&#93;&#91;y&#93; === 1){
  //       			drawWall(x + 1, y + 1);
  //       		}
  //       		if ((x === startX && y === startY) || (x === goalX && y === goalY))
  //       		{
  //       			drawRoute(x + 1, y + 1);
  //       		}
  //       	}
  //       }
		// // 壁を描画
		// function drawWall(x, y) {
  //           ctx.fillStyle = wallColor;
  //           drawRect(x, y);
  //       }
  //       function drawRoute(x, y) {
  //           ctx.fillStyle = routeColor;
  //           drawRect(x, y);
  //       }

  //       function drawRect(x, y){
  //       		ctx.fillRect(
  //       	 	x * wallSize,
  //               y * wallSize,
  //               wallSize,
  //               wallSize);
  //       }
	})();
	</script>
</body>
</html>

interactive Art

addEventListener(‘click’, function(e){})で、push(new Ball(x, y, r))します。ランダム関数の範囲をとる際には、return min + Math.floor(Math.random() * (max – min + 1))と書きます。また、ボールの移動は、x++, y++, バウンドは、x軸、y軸をそれぞれ-1をかけてあげます。

reference
.getBoundingClientRect():returns the size of an element and its position relative to the viewport.
setTimeout bind: http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback
Object.prototype: property represents the Object prototype object.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Intractive Art</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
	</style>
</head>
<body>
	<canvas id="mycanvas" width="500" height="250">
	</canvas>
	<script>
	(function(){
		'use strict';

		var canvas;
		var ctx;
		var Ball;
		var balls = [];
		var Stage;
		var stage;

		canvas = document.getElementById('mycanvas');
		if (!canvas || !canvas.getContext) return false;
		ctx = canvas.getContext('2d');

		function rand(min, max){
			return min + Math.floor(Math.random() * (max - min + 1));
		}

		function adjustPosition(pos, r, max) {
			/*if (x - r < 0) x = r;
			if (y - r < 0) y = r;
			if (x + r > canvas.width) x = canvas.width - r;
			if (y + r > canvas.height) y = canvas.height - r;*/
			if (pos - r < 0){
				return r;
			} else if (pos + r > max){
				return max - r;
			} else {
				return pos;
			}

		}

		canvas.addEventListener('click', function(e){
			var x, y, r;
			var rect;
			/*x = rand(100, 400);
			y = rand(100, 200);*/
			rect = e.target.getBoundingClientRect();
			x = e.clientX - rect.left;
			y = e.clientY - rect.top;

			r = rand(0, 100) < 20 ? rand(50, 80) : rand(10, 35);

			/*if (x - r < 0) x = r;
			if (y - r < 0) y = r;
			if (x + r > canvas.width) x = canvas.width - r;
			if (y + r > canvas.height) y = canvas.height - r;*/
			x = adjustPosition(x, r, canvas.width);
			y = adjustPosition(y, r, canvas.height);
			balls.push(new Ball(x, y, r));
		});

		Ball = function(x, y, r){
			this.x = x;
			this.y = y;
			this.r = r;
			this.vx = rand(-10, 10);
			this.vy = rand(-10, 10);
			this.color = 'hsla(' + rand(50, 100)+ ', ' + rand(40, 80) + '%, ' + rand(50, 60) +'%, ' + Math.random() + ')';
		};

		/*var ball = new Ball(rand(100, 200), rand(100, 200), rand(10, 50));
		ball.draw();*/

		Ball.prototype.draw = function(){
			ctx.beginPath();
				ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
				ctx.fillStyle = this.color;
				ctx.closePath();
				ctx.fill();

		};

		Ball.prototype.move = function(){
			if (this.x + this.r > canvas.width || this.x - this.r < 0){
				this.vx *= -1;
			}
			if (this.y + this.r > canvas.height || this.y - this.r < 0){
				this.vy *= -1;
			}
			this.x += this.vx;
			this.y += this.vy;

		};

		Stage = function(){
			this.update = function(){
					var i;
					this.clear();
			
			for (i = 0; i < balls.length; i++){
				balls&#91;i&#93;.draw();
				balls&#91;i&#93;.move();
			}
			setTimeout(function(){
				this.update();
			}.bind(this), 30);

			};
			this.clear = function(){
				ctx.fillStyle = "#ecf0f1";
				ctx.fillRect(0, 0, canvas.width, canvas.height);
			}
		};

		stage = new Stage();
		stage.update();

	})();
	</script>
</body>
</html>

15puzzle

タイルを動かして、1-15の順番に並べるゲームで、各数字に割り当てるx座標y座標をMathfloorのwidth,heightで割って、配列しています。var moveCountの数字を動かすことによって、ゲームの難易度を変更します。

reference
clientX Property:returns the horizontal coordinate (according to the client area) of the mouse pointer when a mouse event was triggered.The client area is the current window.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>15puzzle</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
	</style>
</head>
<body>
	<canvas id="stage" width="280" height="280">
		Canvas not supported ...
	</canvas>
	<script>
		(function(){
			'use strict';

			var canvas = document.getElementById('stage');
			var context;
			var image;
			var IMAGE_URL = '15puzzle.png';
			var tiles = [];
			var ROW_COUNT = 4;
			var COL_COUNT = 4;
			var PIC_WIDTH = 280;
			var PIC_HEIGHT = 280;
			var TILE_WIDTH = PIC_WIDTH / COL_COUNT;
			var TILE_HEIGHT = PIC_HEIGHT / ROW_COUNT;
			var UDLR = [
				[ 0, -1],
				[ 0, 1],
				[ -1, 0],
				[ 1, 0],
			];
			var moveCount = 3;

			function initTiles(){
				var row, col;
				for (row = 0; row < ROW_COUNT; row++){
					tiles&#91;row&#93; = &#91;&#93;;
					for (col = 0; col < COL_COUNT; col++){
						tiles&#91;row&#93;&#91;col&#93; = row * COL_COUNT + col;
					}
				}
				tiles&#91;ROW_COUNT - 1&#93;&#91;COL_COUNT - 1&#93; = -1;
			}

			function drawPuzzle(){
				var row, col;
				var sx, sy;
				var dx, dy;

				for (row = 0; row < ROW_COUNT; row++){
					for (col = 0; col < COL_COUNT; col++){
						dx = col * TILE_WIDTH;
						dy = row * TILE_HEIGHT;
						if (tiles&#91;row&#93;&#91;col&#93; === -1){
							context.fillStyle = '#eeeeee';
							context.fillRect(dx, dy, TILE_WIDTH, TILE_HEIGHT);
						}else {
						sx = (tiles&#91;row&#93;&#91;col&#93; % COL_COUNT) * TILE_WIDTH;
						sy = Math.floor((tiles&#91;row&#93;&#91;col&#93; / ROW_COUNT)) * TILE_HEIGHT;
				
						context.drawImage(image, sx, sy, TILE_WIDTH, TILE_HEIGHT, dx, dy, TILE_WIDTH, TILE_HEIGHT);
						}
						
					}
				}
	
				/*context.drawImage(image, 0, 0);*/
			}

			function checkResult(){
				var row, col;
				for (row = 0; row < ROW_COUNT; row++){
					for (col = 0; col < COL_COUNT; col++){
						if (row === ROW_COUNT -1 && col === COL_COUNT -1){
							return true;
						}
						if (tiles&#91;row&#93;&#91;col&#93; !== row * COL_COUNT + col){
							return false;
						}
				}
			}

			}
			function moveBlank(count){
				var blankRow, blankCol;
				var targetPosition;
				var targetRow, targetCol;

				blankRow = ROW_COUNT -1;
				blankCol = COL_COUNT -1;

				while(true){
				targetPosition = Math.floor(Math.random() * UDLR.length);
				targetRow = blankRow + UDLR&#91;targetPosition&#93;&#91;1&#93;;
				targetCol = blankCol + UDLR&#91;targetPosition&#93;&#91;0&#93;;
				if(targetRow < 0 || targetRow >= ROW_COUNT){
					continue;
				}
				if(targetCol < 0 || targetCol >= COL_COUNT){
					continue;
				}
				tiles[blankRow][blankCol] = tiles[targetRow][targetCol];
				tiles[targetRow][targetCol] = -1;
				blankRow = targetRow;
				blankCol = targetCol;
				if(!--count){
					break;
				}
				} 
			}

			if (!canvas.getContext){
				alert('canvas not supported ...');
				return
			}
			context = canvas.getContext('2d');

			image = document.createElement('img');
			image.src = IMAGE_URL;
			image.addEventListener('load', function(){
				initTiles();
				moveBlank(moveCount);
				drawPuzzle();
			});

			canvas.addEventListener('click', function(e){
				var x, y;
				var rect;
				var row, col;
				var i;
				var targetRow, targetCol;
				rect = e.target.getBoundingClientRect();
				x = e.clientX - rect.left;
				y = e.clientY - rect.top;
				row = Math.floor(y / TILE_HEIGHT);
				col = Math.floor(x / TILE_WIDTH);
				if (tiles[row][col] === -1){
					return;
				}
				 for (i = 0; i < UDLR.length; i++) {
       			 targetRow = row + UDLR&#91;i&#93;&#91;1&#93;;
      			  targetCol = col + UDLR&#91;i&#93;&#91;0&#93;;
      			  if (targetRow < 0 || targetRow >= ROW_COUNT) {
      		  	 	 continue;
     			   }
     			  if (targetCol < 0 || targetCol >= COL_COUNT) {
     		     	 continue;
    			    }
					if (tiles[targetRow][targetCol] === -1) {
         			 tiles[targetRow][targetCol] = tiles[row][col];
         			 tiles[row][col] = -1;
       				   drawPuzzle();
       				   if (checkResult()){
       				   	alert('Game Clear!')
       				   }
						break;
					}
				}
			});
		})();
	</script>
</body>
</html>

神経衰弱

レベルに合わせて、配列を作成し、CSSでflipし、judgeして、正しければ次のレベルに移行します。

-reference
Emmet Toggle Comment: ctr + shift + /
CSS3 backface-visibility Property: The backface-visibility property defines whether or not an element should be visible when not facing the screen.This property is useful when an element is rotated, and you do not want to see its backside.
first-child:is used to select the specified selector, only if it is the first child of its parent.
.textContent:ノードとその子孫のテキスト内容を取得、または設定
.children:Get the children of each element in the set of matched elements, optionally filtered by a selector.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Get same number</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		body {
			margin: 0;
			background: #00d4f0;
			text-align: center;
			font-family: Arial, sans-serif;
			color: #fff;
		}
		#stage{
			margin: 80px auto 30px;
			width: 600px;
		}
		.card-container {
			margin: 0 10px 20px 0;
			cursor: pointer;
			display: inline-block;
			width: 50px;
			height: 60px;
			font-size: 24px;
			font-weight: bold;
			line-height: 60px;
			position: relative;
			perspective: 100px;
		}
		.card {
			width: 100%;
			height: 100%;
			position: absolute;
			transform-style: preserve-3d;
			transition: transform .8s;
		}
		.card.open {
			transform: rotateY(180deg);
		}
		.card-back, .card-front {
			display: block;
			width: 100%;
			height: 100%;
			border-radius: 5px;
			position: absolute;
			backface-visibility: hidden;
		}
		.card-back{
			background: #03a9f4;
		}
		.card-front{
			background: #fff;
			color: #333;
			transform: rotateY(180deg);
		}
		#btn {
			margin: 0 auto;
			width: 200px;
			padding: 10px;
			background: #0af;
			border-radius: 5px;
			cursor: pointer;
			opacity: 0;
			transition: opacity .5s;
		}
		#btn.visible{
			opacity: 1;
		}
	</style>
</head>
<body>
	<div id="stage">
	</div>
	<div id="btn">Next Stage?</div>
	<script>
	(function(){
		var cards = [],
		    level = 2,
		    flipCount = 0,
		    correctCount = 0,
		    firstCard = null,
		    secondCard = null;
		    btn,
		    stage;

		  btn = document.getElementById('btn');
		  stage = document.getElementById('stage');

		init();

		function init(){

			correctCount = 0;
			btn.className = '';

			while(stage.firstChild) stage.removeChild(stage.firstChild);

			for (var i = 1; i <= level; i++){
				cards&#91;cards.length&#93; = createCard(i);
				cards&#91;cards.length&#93; = createCard(i);
			}

			while (cards.length){
				var pos = Math.floor(Math.random() * cards.length);
				stage.appendChild(cards.splice(pos, 1)&#91;0&#93;);
			}
		}

		function createCard(num){
			var inner,
				card,
				container;

			inner = '<div class="card-back">?</div><div class="card-front">*</div>';

			card = document.createElement('div');
			card.className = 'card';
			card.innerHTML = inner.replace('*', num);

			container = document.createElement('div');
			container.className = 'card-container';
			container.appendChild(card);
			card.addEventListener('click', function(){
				flipCard(this);
			});

			return container;
		}

		function flipCard(card){
			if (firstCard !== null && secondCard !== null){
				return;
			}

			if (card.className.indexOf('open') === -1){
				card.className = 'card open';
			} else {
				return;
			}
			flipCount++;
			if (flipCount % 2 === 1) {
				firstCard = card;
			} else {
				secondCard = card;
				setTimeout(function(){
					judge();
				}, 900);
			}
		}

		function judge(){
			if (firstCard.children[1].textContent === secondCard.children[1].textContent){
				correctCount++;
				//console.log(correctCount);
				if (correctCount === level){
					btn.className = 'visible';
				}
			} else {
				firstCard.className = 'card';
				secondCard.className = 'card';
			}
			firstCard = null;
			secondCard = null;
		}

		btn.addEventListener('click', function(){
			level++;
			init();
		});
	})();
	</script>
</body>
</html>

数押しゲーム

addEventListener(‘click’, function(){}で、クリックごとに、btn inactiveのクラスを追加していってます。数字の初期値はランダム、時間はsetTimeoutで、現在時間からスタート時間を引いています。

reference
appendChild(): method appends a node as the last child of a node.
Tip: If you want create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.
Document.createElement() :method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized. In a XUL document, it creates the specified XUL element. In other documents, it creates an element with a null namespace URI.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Run Time for Button touch</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		body {
			background: #e0e0e0;
			font-family: Arial, sans-serif;
			text-align: center;
			color: #0088cc;
			font-size: 16px;
		}
		#scoreArea{
			text-shadow: 0 1px 0 rgba(255, 255,255, 0.5);
			margin: 30px auto;
		}
		#scoreText{
			font-weight: bold;
			font-size: 24px;
		}
		#startButton{
			margin: 30px auto;
			width: 180px;
			border-radius: 5px;
			box-shadow: 0 4px 0 #e91b0c;
			background: #f44336;
			color: #fff;
			cursor: pointer;
			padding: 7px;
		}
		#startButton:hover{
			opacity: 0.8;
		}
		#startButton.pushed{
			margin-top: 32px;
			box-shadow: 0 2px 0 #e91b0c;
		}
		.btn {
			position: relative;
			display: inline-block;
			width: 30px;
			padding: 7px;
			border-radius: 5px;
			box-shadow: 0 4px 0 #0088cc;
			color: #fff;
			background: #00aaff;
			cursor: pointer;
			margin-bottom: 10px;
		}
		.btn.hidden:after{
			content: '?';
			position: absolute;
			top: 0;
			left: 0;
			width: 30px;
			padding: 7px;
			border-radius: 5px;
			background: #00aaff;
		}
		.btn + .btn {
			margin-left: 10px;
		}
		.btn.inactive {
			opacity: 0.5;
		}
	</style>
</head>
<body>
	<div id="scoreArea">Your Score: <span id="scoreText">0.0</span></div>
	<div id="board">
		<!--<div class="btn">0</div>
		<div class="btn">1</div><br>
		<div class="btn">2</div>
		<div class="btn">3</div> -->
	</div>
	<div id="startButton" class="pushed">START</div>
	<script>
	(function(){
		'use strict';
		var size = 3;
		var currentNum = 0;
		var startTime;
		var timerId;

		var board = document.getElementById('board');
		var scoreText = document.getElementById('scoreText');
		var startButton = document.getElementById('startButton');

		initBoard();

		startButton.addEventListener('click', function(){
			initBoard();
			var btns = document.getElementsByClassName('btn');
			for (var i = 0; i < btns.length; i++){
				btns&#91;i&#93;.className = 'btn';
			}
			currentNum = 0;
			startTime = Date.now();
			if(timerId !== null) clearTimeout(timerId);
			runTimer();
		});

		startButton.addEventListener('mousedown', function(){
			this.className = 'pushed';
		});

		startButton.addEventListener('mouseup', function(){
			this.className = '';
		});


		function runTimer(){
			scoreText.innerHTML = ((Date.now() - startTime) / 1000).toFixed(2);
			timerId = setTimeout(function(){
				runTimer();
			}, 10);
		}

			function createButton(num){
				var button;
				button = document.createElement('div');
				button.className = 'btn hidden';
				button.innerHTML = num;
				button.addEventListener('click', function(){
					if ((this.innerHTML - 0) === currentNum){
						this.className = 'btn inactive';
						currentNum++;
					}
					if (currentNum == size * size){
						clearTimeout(timerId);
					}
				});
				return button;
			}

			function initBoard(){
			var buttons = &#91;&#93;;

			while (board.firstChild){
				board.removeChild(board.firstChild);
			}

			for (var i = 0; i < size * size; i ++){
				buttons.push(createButton(i));
			}
			while (buttons.length){
				var button = buttons.splice(Math.floor(Math.random() * buttons.length), 1);
				board.appendChild(button&#91;0&#93;);
				if (buttons.length % size === 0){
					board.appendChild(document.createElement('br'));
				}
			}
		}
	})();
	</script>
</body>
</html>

タイピングゲーム

fromCharCodeとkeyCodeで、タイピングのcharacterを取得し、予め用意された配列とマッチするか判定しています。マッチしていれば、位置文字ずつ”_”に文字を変換し、残りの文字をsubstring()で取得します。タイマーは、setTimeout()で1000ミリ秒ごとに減らしていき、0になったら、alert()を表示させます。

リフェレンス
fromCharCode() Method:converts Unicode values into characters.
Note: This is a static method of the String object, and the syntax is always String.fromCharCode().
substring():extracts the characters from a string, between two specified indices, and returns the new sub string.
setTimeout():calls a function or evaluates an expression after a specified number of milliseconds.
Tip: 1000 ms = 1 second.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>タイピングゲーム</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
	body {
		padding-top: 40;
		font-family: 'Courier New', sans-serif;
		text-align: center;
	}
	#target {
		font-size: 48px;
		letter-spacing: 3px;
	}
	.info {
		color: #ccc;
	}
	</style>
</head>
<body>
	<p id="target"></p>
	<p class="info">
		Letters count: <span id="score"></span>
		Miss count: <span id="miss"></span>
		Remaining Time: <span id="timer"></span>
	</p>
	<script>
	(function(){
		'use strict';

		var words = [
		'java',
		'python',
		'ruby',
		'go',
		'c',
		'javascript',
		'cobol',
		'php',
		];
		var currentWord;
		var currentLocation;
		var score;
		var miss;
		var timer;
		var target = document.getElementById('target');
		var scoreLabel = document.getElementById('score');
		var missLabel = document.getElementById('miss');
		var timerLabel = document.getElementById('timer');
		var isStarted;
		var timerId;

		function init(){
			currentWord = 'click to start';
			currentLocation = 0;
			score = 0;
			miss = 0;
			timer = 7;
			target.innerHTML = currentWord;
			scoreLabel.innerHTML = score;
			missLabel.innerHTML = miss;
			timerLabel.innerHTML = timer;
			isStarted = false;
		}
		
		init();

		function updateTimer(){
			timerId = setTimeout(function(){
				timer--;
				timerLabel.innerHTML = timer;
				if (timer <= 0){
					// alert('game over');
					var accuracy = (score + miss) === 0 ? '0.00' : (score / (score + miss) * 100).toFixed(2);
					alert(score + ' letters, ' + miss + ' miss!' +  accuracy + ' % accuracy');
					clearTimeout(TimerId);
					init();
					return;
				}
				updateTimer();
			}, 1000);
		}

		function setTarget(){
			currentWord = words&#91;Math.floor(Math.random()* words.length)&#93;;
			target.innerHTML = currentWord;
			currentLocation = 0;
		}

		window.addEventListener('click', function() {
			if (!isStarted){
				isStarted = true;
				setTarget();
				updateTimer();
			}
			
		});

		window.addEventListener('keyup', function(e) {
			if (!isStarted){
				return;
			}
			if (String.fromCharCode(e.keyCode) ===
				currentWord&#91;currentLocation&#93;.toUpperCase()){
				currentLocation++;
				var placeholder = '';
				for (var i = 0; i < currentLocation; i++){
					placeholder += '_';
				}
				target.innerHTML = placeholder + currentWord.substring(currentLocation);
				score++;
				scoreLabel.innerHTML = score;
				if (currentLocation === currentWord.length){
					setTarget();
				}
			} else {
				miss++;
				missLabel.innerHTML = miss;
			}
		});
	})();
	</script>
</body>
</html>

テーブルのソート

ソート・並び替えは、一旦、表示を全て消して、配列の中身を並び替えて再表示しています。ソートの関数はarr.sort(function(a, b){});を使います。
並び替え関数

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

リフェレンス:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>テーブルのソート機能</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
	<link rel="stylesheet" href="css/styles.css">
	<style>
	</style>
</head>
<body>
	<table>
	<thead>
		<tr>
			<th data-type="string">Name</th>
			<th data-type="string">Team</th>
			<th data-type="number">Score</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>murakami</td>
			<td>orange</td>
			<td class="score">35</td>
		</tr>
		<tr>
			<td>Kuriyama</td>
			<td>orange</td>
			<td class="score">5</td>
		</tr>
		<tr>
			<td>murata</td>
			<td>Yellow</td>
			<td class="score">77</td>
		</tr>
		<tr>
			<td>sakurai</td>
			<td>green</td>
			<td class="score">68</td>
		</tr>
		<tr>
			<td>midokura</td>
			<td>yellow</td>
			<td class="score">48</td>
		</tr>
		<tr>
			<td>kimoto</td>
			<td>green</td>
			<td class="score">97</td>
		</tr>
	</tbody>
	</table>
	<div>
	</div>
	<script src="js/main.js">
	</script>
</body>
</html>

js.main.js

(function(){
	'use strict';

	 var ths = document.getElementsByTagName('th');
	 var sortOrder = 1;

	 function rebuildTobody(rows){
	 		var tbody = document.querySelector('tbody');

	 		while(tbody.firstChild){
	 			tbody.removeChild(tbody.firstChild);
	 		}
	 		var i;
	 		for(i = 0; i < rows.length; i++){
	 			tbody.appendChild(rows[i]);
	 		}
	 	}

	 	function updateClassName(th){
			var k;
	 		for(k = 0; k < ths.length; k++){
	 		ths[k].className = '';
	 		}
	 		th.className = sortOrder === 1 ? 'asc' : 'desc';
	 	}

	 	function compare(a, b, col, type){
	 			var _a = a.children[col].textContent;
	 			var _b = b.children[col].textContent;
	 			if (type === "number"){
	 			_a = _a * 1;
	 			_b = _b * 1;
	 			}
	 			else if (type === "string") {
	 			_a = _a.toLowerCase();
	 			_b = _b.toLowerCase();
	 			}
	 			if (_a < _b){
	 				return -1;
	 			}
	 			if (_a > _b) {
	 				return 1;
	 			}
	 			return 0;
	 	}

	 	function sortRows(th){
	 		var rows = Array.prototype.slice.call(document.querySelectorAll('tbody > tr'));
	 		var col = th.cellIndex;
	 		var type = th.dataset.type;

	 		rows.sort(function(a, b){
	 			return compare(a, b, col, type) * sortOrder;
	 		});
	 		return rows;
	 	}

	 	function setup(){
	 		var i;
	 		for (i = 0; i < ths.length; i++){
	 		ths[i].addEventListener('click', function(){
	 		var rows;
	 		rows = sortRows(this);
	 		rebuildTobody(rows);	 		
	 		updateClassName(this);
	 		sortOrder *= -1;
	 	});
	  }
	}
	 	setup();
})();

css/styles.css

body {
	font-size: 16px;
	font-family: Verdana, sans-serif;
}
table {
	width: 540px;
	margin: 20px auto;
	border-collapse: collapse;
}
th, td {
	width: 180px;
	box-sizing: border-box;
	border: 1px solid #e9eae8;
	padding: 8px 20px;
}
tbody tr:nth-child(odd){
	background: #f8f8f8;
}
.score {
	text-align:right;
}
th {
	cursor: pointer;
}

th:after {
	content: '\f0dc';
	font-family: FontAwesome;
	font-size: 12px;
	color: #ccc;
	float: right;
	padding-top: 4px;
	font-weight: normal;
}

th.asc:after {
	content: '\f0de';
	font-family: FontAwesome;
	color: #000;
}
th.desc:after {
	content: '\f0dd';
	font-family: FontAwesome;
	color: #000;
}

単語帳

表と裏をdocument.getElementByIdで、divタグのidから呼び出しています。CSS3でカードflipはtransform: rotateY(180deg);と表現します。

リフェレンス
KeyCode:The KeyboardEvent.keyCode read-only property represents a system and implementation dependent numerical code identifying the unmodified value of the pressed key.

keyup:Bind an event handler to the “keyup” JavaScript event, or trigger that event on an element.

コード

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>単語帳</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
	body {
		margin: 0;
		background: #e0e0e0;
		text-align: center;
		font-family: Verdana, sans-serif;
		color: #fff;
	}
	#btn {
		width: 200px;
		margin: 0 auto;
		padding: 7px;
		border-radius: 5px;
		background: #00aaff;
		box-shadow: 0 4px 0 #0088cc;
		cursor: pointer;
	}
	#btn:hover{
		opacity: 0.8;
	}
	#card {
		margin: 60px auto 20px;
		width: 400px;
		height: 100px;
		cursor: pointer;
		font-size: 38px;
		line-height: 100px;
		perspective: 100px;
		transform-style: preserve-3d;
		transition: transform .8s;
	}
	#card-front, #card-back {
		display: block;
		width: 100%;
		height: 100%;
		border-radius: 5px;
		position: absolute;
		backface-visibility: hidden;
	}
	#card-front {
		background: #fff;
		color: #333;
	}
	#card-back {
		background: #00aaff;
		transform: rotateY(180deg);
	}
	.open {
		transform: rotateY(180deg);
	}
	</style>
</head>
<body>
	<div id="card">
		<div id="card-front"></div>
		<div id="card-back"></div>
	</div>
	<div id="btn">NEXT</div>
	<script>
	(function(){
		'use strict'

		var words = [
			{'en': 'read', 'ja':'読む'},
			{'en': 'write', 'ja':'書く'},
			{'en': 'eat', 'ja':'食べる'},
			{'en': 'run', 'ja':'走る'},
			{'en': 'walk', 'ja':'歩く'}
		];

		var card = document.getElementById('card');
		var cardFront = document.getElementById('card-front');
		var cardBack = document.getElementById('card-back');
		var btn = document.getElementById('btn');

		card.addEventListener('click', function(){
			flip();
		});
		btn.addEventListener('click', function(){
			next();
		});

		function next(){
			if (card.className === 'open') {
				card.addEventListener('transitioned', setCard);
				flip();
			} else {
				setCard();
			}

		}

		function setCard(){
			var num = Math.floor(Math.random() * words.length);
			cardFront.innerHTML = words[num]['en'];
			cardBack.innerHTML = words[num]['ja'];
			card.removeEventListener('transitioned', setCard);
		}

		setCard();

		window.addEventListener('keyup', function(e){
			if (e.keyCode === 70){
				flip();
			} else if (e.keyCode === 78){
				next();
			}
		});

		function flip(){
			card.className = card.className === '' ? 'open' : '';
		}
	
	})();
	</script>
</body>
</html>

スロットマシーン

classNameにactive、inactiveをつけて、opacityを変えます。また、addEventListenerで、クリックされた際に、Math.floor(Math.random() * (n + 1))で、ランダムな数値を取得し、配列に返し、それぞれの数字が一致するか、チェックして、opacityを変えます。実際のスロットは、もう少し複雑な設定方法だと思いますが、原理としては近いものがあるのではないでしょうか。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Slot Machine</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		body {
			background: #e0e0e0;
			font-family: Arial, sans-serif;
			text-align: center;
			font-size: 16px;
			margin-top: 30px;
		}
		.panel {
			display: inline-block;
			width: 60px;
			padding: 7px;
			border-radius: 5px;
			margin-bottom: 15px;
			color: #00aaff;
			font-weight: bold;
			font-size: 32px;
			line-height: 64px;
			background: #fff;
		}
		.panel + .panel {
			margin-left: 10px;
		}
		.panel.unmatched {
			opacity: 0.5;
		}
		.btn {
			display: inline-block;
			width: 60px;
			padding: 7px;
			border-radius: 5px;
			margin-bottom: 15px;
			color: #fff;
			box-shadow: 0 4px 0 #0088cc;
			background: #00aaff;
			cursor: pointer;
		}
		.btn + .btn {
			margin-left: 10px;
		}
		.btn.inactive{
			opacity: 0.5;
		}
		#spinButton {
			margin: 0 auto;
			width: 240px;
			padding: 7px;
			border-radius: 5px;
			color: #fff;
			box-shadow: 0 4px 0 #e91b0c;
			background: #f44336;
			cursor: pointer;
		}
		#spin.inactive{
			opacity: 0.5;
		}
	</style>
</head>
<body>
	<div>
	  <div class="panel" id="panel0">?</div>
	  <div class="panel" id="panel1">?</div>
	  <div class="panel" id="panel2">?</div>
	</div>
	<div>
		<div class="btn inactive" id="btn0">STOP</div>
		<div class="btn inactive" id="btn1">STOP</div>
		<div class="btn inactive" id="btn2">STOP</div>
	</div>
	<div id="spinButton">SPIN</div>
	<script>
		(function(){
			'use strict';

			var panels = ['1', '3', '5', '7'];
			var timers = [];
			var results = [];
			var stopCount = 0;
			var isPlaying = false;

			var panel0 = document.getElementById('panel0');
			var panel1 = document.getElementById('panel1');
			var panel2 = document.getElementById('panel2');
			var btn0 = document.getElementById('btn0');
			var btn1 = document.getElementById('btn1');
			var btn2 = document.getElementById('btn2');
			var spinButton = document.getElementById('spinButton');

			spinButton.addEventListener('click', function(){
				if (isPlaying) return;
				isPlaying = true;
				this.className = 'inactive';
				btn0.className = 'btn';
				btn1.className = 'btn';
				btn2.className = 'btn';
				panel0.className = 'panel';
				panel1.className = 'panel';
				panel2.className = 'panel';

				runSlot(0, panel0);
				runSlot(1, panel1);
				runSlot(2, panel2);
			});

			function runSlot(n, panel){
				panel.innerHTML = panels[Math.floor(Math.random() * panels.length)];
				timers[n] = setTimeout(function(){
					runSlot(n, panel)
				}, 50);
			}

			btn0.addEventListener('click', function(){
				stopSlot(0, panel0, this);
			});
			btn1.addEventListener('click', function(){
				stopSlot(1, panel1, this);
			});
			btn2.addEventListener('click', function(){
				stopSlot(2, panel2, this);
			});

			function stopSlot(n, panel, btn){
				if (!isPlaying || results[n] !== undefined) return;
				btn.className = 'btn inactive';
				clearTimeout(timers[n]);
				results[n] = panel.innerHTML;
				stopCount++;

				if (stopCount === 3){
					checkResults();

					isPlaying = false;
					timers = [];
					results = [];
					stopCount = 0;
					spintButton.ClassName = '';
				}
			}

			function checkResults(){
				if (results[0] !== results[1] && results[0] !== results[2]) {
						panel0.className = 'panel unmatched';
			}
				if (results[1] !== results[0] && results[1] !== results[2]) {
						panel1.className = 'panel unmatched';
			}
				if (results[2] !== results[0] && results[2] !== results[1]) {
						panel2.className = 'panel unmatched';
			}
		}
		})();
	</script>
</body>
</html>