Cloud9

Cloud9はクラウドの統合開発環境で、ブラウザ上で手軽に開発環境を用意することができます。
Cloud9

sign inすると、クレジットカードの入力項目があり、ドキッとしますが、登録によるチャージはありません。
%e7%84%a1%e9%a1%8c

初期画面
%e7%84%a1%e9%a1%8c

インターフェイスはdreamweaverっぽいですが、嫌いではないですね。javaのコンソールもあります。
%e7%84%a1%e9%a1%8c

apacheを起動して、サーバー上で確認することも可能です。
JavaScript Consoleはブラウザで閲覧します。php, ruby, pythonはコマンドラインから作っていきましょう。

sqliteはsqliteコマンド、mysqlはmysql-ctl cliを打ち込みます。

cloud9を使えば、railsも簡単に環境をつくることができます。
%e7%84%a1%e9%a1%8c

jQuery thumbnail スライドショー

タイマー処理を使って、自動再生のスライドショーを作成します。
timer = setTimeout(function(){
autoPlay();

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQueryスライドショー</title>
    <style>
    body {
      margin: 10px auto;
      text-align: center;
    }
     .thumbnail{
          width: 125px;
          height:83px;
          opacity: 0.5;
          cursor:pointer;
     }
     .current {
      opacity: 1;
     }
     .thumbnail + .thumbnail {
      margin-left: 4px;
     }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <div id="thumbnails"></div>
      <div id="main"></div>
      <div id="nav">
          <button id="prev">&laquo; 前へ</button>
          <button id="next">次へ&raquo; </button>
          <button id="play">再生</button>
          <button id="stop">停止</button>
      </div>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
      $(function(){
          var files = [
            '01.jpg',
            '02.jpg',
            '03.jpg',
            '04.jpg'
          ];
            var img;
            var timer;
            var currentNum = 0;
            var nowPlaying = false;
            for (var i = 0; i < files.length; i++){
              img = $('<img>').attr('src', files[i]).addClass('thumbnail');
              $('#thumbnails').append(img);
            }
            $('#main').append(
                $('<img>').attr('src', files[0])
              );
            $('.thumbnail:first').addClass('current');
            $('.thumbnail').click(function(){
              $('#main img').attr('src', $(this).attr('src'));
              currentNum = $(this).index();
              $(this).addClass('current').siblings().removeClass('current');
            });
            $('#prev').click(function(){
              currentNum--;
              if (currentNum < 0){
                currentNum = files.length -1;
              }
              $('#main img').attr('src', files&#91;currentNum&#93;);
              $('.thumbnail').removeClass('current');
              $('.thumbnail').eq(currentNum).addClass('current');
            });
            $('#next').click(function(){
              currentNum++;
              if (currentNum > files.length - 1){
                currentNum = 0;
              }
              $('#main img').attr('src', files[currentNum]);
              $('.thumbnail').removeClass('current');
              $('.thumbnail').eq(currentNum).addClass('current');
            });
            function autoPlay(){
              $('#next').click();
              timer = setTimeout(function(){
                  autoPlay();
              }, 1000);
            }
            $('#play').click(function(){
                  if (nowPlaying) return;
                  nowPlaying = true;
                autoPlay();
            });
            $('#stop').click(function(){
                    clearTimeout(timer);
                    nowPlaying = false;
            });
      });
      </script>
  </body>
</html>

%e7%84%a1%e9%a1%8c

jQuery 間違い探しゲーム

ランダムで、数列に一か所に文字を挿入します。
var offset = Math.floor(Math.random() * chars.length);
chars.splice(offset, 1, seikai);

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>間違い探しゲーム</title>
    <style>
        span {
          cusor:pointer;
        }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <h1>間違い探しゲーム</h1>
      <p><input type="button" value="開始!" onclick="gameStart();"></p>
      <div id="score"></div>
      <div id="cells"></div>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
          var level = 0;
          var games = [
              ['問', '間'],
              ['大', '太'],
              ['白', '臼']
          ];
          var MAX_LEVEL = games.length - 1;
          var DIM_FIRST = 5;
          var DIM_DELTA = 3;
          var dim = DIM_FIRST;
          var t1;
          var t2;

          function gameStart(){
            var dummy = games[level][0];
            var seikai =games[level][1];

            if (level == 0){
              $('#score').empty();
              t1 = new Date().getTime();
            }
            

            var cells = '';
            for (var i = 1; i <= dim * dim; i++){
              cells += '<span id="s' + i + '"></span>';
              if (i % dim == 0){
                cells += '<br />';
              }
            }
            $('#cells').html(cells);

            var chars = [];
            for (var i = 0; i < dim * dim; i++){
              chars.push(dummy);
            }

            var offset = Math.floor(Math.random() * chars.length);
            chars.splice(offset, 1, seikai);

            // console.log(chars);
            for (var i = 1; i <= chars.length; i++){
              $('#s'+i).text(chars&#91;i-1&#93;);
              $('#s'+i).click(function(){
                if ($(this).text() == seikai){
                  level++;
                  dim += DIM_DELTA;
                  if (level > MAX_LEVEL){
                        t2 = new Date().getTime();
                      $('#score').text('Your score is '+(t2 - t1)/1000 +'!!');
                      level = 0;
                      dim = DIM_FIRST;
                      return false;
                  }
                  gameStart();
                }
              });
            }

          }
      </script>
  </body>
</html>

%e7%84%a1%e9%a1%8c

jQuery ↑にスクロール

アイコンはfadeIn、fadeOutを使用し、アニメーションで何秒で戻るか指定します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>スクロール</title>
    <style>
        body {
          text-align: center;
        }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <h1>スクロール</h1>
          <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <p>hello</p>
    <div id="back-to-top" style="position:fixed;right:5px; bottom:5px"><a href="#">↑</a></div>
    <div id="pos" style="position:fixed; left:5px; bottom:5px">

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
      $(function(){
          $('#back-to-top').hide();

          $(window).scroll(function(){
              $('#pos').text($(this).scrollTop());
              if ($(this).scrollTop() > 60 ) {
                $('#back-to-top').fadeIn();
              } else {
                $('#back-to-top').fadeOut();
              }
          });
          $('#back-to-top a').click(function(){
              $('body').animate({
                scrollTop:0
              }, 500);
              return false;
          });
      });
      </script>
  </body>
</html>

%e7%84%a1%e9%a1%8c

JavaScript キャラ診断をツイートしよう

ランダム関数は、Math.floor(Math.random() * types.length、tweetリンクは、twitter developerのweb intentsを使います。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>キャラ診断</title>
    <style>
        body {
          text-align: center;
        }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <h1>キャラ診断</h1>
      <p><input type="text" id="name" value=""></p>
      <p><input type="button" id="getResult" value="診断"></p>
      <h2>診断結果</h2>
      <p id="result">こちらに結果が表示されます。</p>
      <div id="tweet"></div>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
          $(function(){
              $("#getResult").click(function(){
                  var name = $("#name").val();
                  // console.log(name);

                    if (name === ""){
                      alert("名前を入力してください!");
                      return;
                    }
                  // タイプの定義
                  var types = ["勇者","魔法使い","戦士","遊び人","スーパースター"];
                  var type = types[Math.floor(Math.random() * types.length)];

                  var character = ["賢い","勇ましい","かわいい","情けない","人気の"];
                  var character = character[Math.floor(Math.random() * character.length)];

                  var result = name + "さんは「" + character + type + "」です。";
                  $("#result").text(result);

                  var tweetLink = "<a href='https://twitter.com/intent/tweet?text="+ encodeURIComponent(result) +"&hashtags=chara' target='_blank'>ツイートする</a>";
                  $("#tweet").html(tweetLink);
              });
          });
      </script>
  </body>
</html>

%e7%84%a1%e9%a1%8c

Ajaxで複数の値を返す

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQeury</title>
    <style>
    .myStyle{
      border:5px solid green;
      font-size:48px;
    }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <p>jQuery</p>

      <p>
        <input type="text" name="name" id="name">
        <input type="button" id="greet" value="Greet!">
      </p>
      <div id="result"></div>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
        $(function(){

          $('#greet').click(function(){

            $.get('greet.php', {
              name: $('#name').val()
            }, function(data){
                $('#result').html(data.message + '(' + data.length + ')');
            });
          });
        });
      </script>
  </body>
</html>
<?php

// echo htmlspecialchars("hi!" . $_GET&#91;"name"&#93;, ENT_QUOTES, "utf-8");

$rs = array(
  "message" => htmlspecialchars("hi!" . $_GET["name"], ENT_QUOTES, "utf-8"),
  "length" => strlen($_GET["name"])
);

header('Content-Type: application/json; charset=utf-8');
echo json_encode($rs);

%e7%84%a1%e9%a1%8c

Ajax

Ajaxは非同期通信、サーバー側からページの更新なく情報を読み出す技術です。
index.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQeury</title>
    <style>
    .myStyle{
      border:5px solid green;
      font-size:48px;
    }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <p>jQueryの練習</p>

      <button>もっと読む</button>
      <div id="result"></div>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
        $(function(){

          $('button').click(function(){
            $('#result').load('more.html');
          });
        });
      </script>
  </body>
</html>

more.html

<p id="message">メッセージです!</p>

jquery

jQuery基礎

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
        $(function(){
            $('p').css('color','red').hide('slow');
        });
      </script>

セレクタの指定

<script>
        $(function(){
            $(".item").css('color', 'red');
        });
</script>

隣接セレクタ

<script>
        $(function(){
            $(" .item + .item").css('color', 'red');
        });
</script>

フィルタ: eq(), gt(), lt(), even, odd, contains(),first, last

<script>
        $(function(){
            $("#sub > li:contains('4')").css('color', 'red');
        });
</script>

メソッドを使ったDOM要素指定:parent(), children(), next(), prev(), siblings()

      <script>
        $(function(){
            $("#sub > li:eq(2)").siblings().css('color', 'red');
        });
      </script>

属性セレクタ: =, !=, *=, ^=, $=

<script>
        $(function(){
            $('a[href!="http://google.com"]').css('background', 'red');
        });
      </script>

css、addClass、removeClass

      <script>
        $(function(){
            //$('p').css('color', 'red').css('background', 'blue');
            //console.log($('p').css('color'));
            $('p').addClass('myStyle');
        });
      </script>

attribute, dataメソッド

$(function(){
            // attr
            console.log($('a').attr('href'));
            $('a').attr('href', 'http://google.co.jp');
            // data
            console.log($('a').data('sitename'));

});

タグの中身を操作: text, html, val, remove, empty

$(function(){
            // $('p').html('<a href="">click me!</a>');
            // console.log($('input').val());
            // $('input').val('hello, again!');
            $('p').empty();
        });

before, after, prepend, append

$(function(){
            var li = $('<li>').text('just added');
            // $('ul > li:eq(1)').before(li);
            // li.insertBefore($('ul > li:eq(1)'));

            // $('ul').prepend(li);
            // $('ul').append(li);
            li.appendTo($('ul'));
        });

コールバック関数 :hide, show, fadeOut, fadeIn, toggle

$(function(){
            // $('#box').hide(800);
            // $('#box').fadeOut(800);
            // $('#box').toggle(800);
            // $('#box').toggle(800);
            // $('#box').toggle(800);
            $('#box').fadeOut(800, function(){
                alert("gone!");
              });
        });

イベントの利用

$(function(){
          // $('#box').click(function(){
          //      alert("hi!");
          // });
          $('#box')
          .mouseover(function(){
                $(this).css('background', 'green');
           })
          .mouseout(function(){
                $(this).css('background', 'red');
           })
          .mousemove(function(e){
                $(this).text(e.pageX);
           })
        });

focus, blur, change

<script>
        $(function(){
            $('#name')
            .focus(function(){
                $(this).css('background', 'red');
            })
            .blur(function(){
                $(this).css('background', 'white');
            });
            $('#members').change(function(){
                alert('changed!');
            });
        });
      </script>

onメソッド

$(function(){
            $('button').click(function(){
                var p = $('<p>').text('vanish!').addClass('vanish');
                $(this).before(p);
            })

            $('body').on('click', '.vanish', function(){
                $(this).remove();
            });
        });

JavaScript 文字数チェック

入力文字数をkeyupによるthis.value.lengthで取得し、条件分岐で、CSSの要素を変える処理を作ります。

html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comment</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
        <div class="container">
            <textarea id="comment" placeholder="your comment here"></textarea>
            <div class="btn">Submimt</div>
            <p><span id="label"></span> characters left</p>
            
      <script src="myscript.js">
      </script>
  </body>
</html>

styles.css

@charset "utf-8";

body {
	font-family: Verdana, sans-serif;
	font-size: 16px;
	background: #e0e0e0;
}

.container {
	width: 400px;
	margin: 30px auto;
}

textarea {
	width: 400px;
	box-sizing: border-box;
	height: 200px;
	padding: 14px;
	font-size: 16px;
	border: none;
	border-radius: 5px;
	margin-bottom: 14px;
	line-height: 1.5;
}
textarea:focus {
	outline: none;
}

p {
	color: #333;
	font-size: 14px;
	margin: 0;
	padding-top:8px;
}

#label{
	font-weight: bold;
}

.btn {
	display: inline-block;
	width: 150px;
	background: #00aaff;
	padding: 5px;
	color: #fff;
	border-radius: 5px;
	text-align: center;
	cursor: pointer;
	box-shadow: 0 4px 0 #0088cc;
	float: right;
}

.warning {
	color:red;
}

myscript.js

(function(){
		'use strict';

		var comment = document.getElementById('comment');
		var label = document.getElementById('label');

		var LIMIT = 20;
		var WARNING = 10;

		label.innerHTML = LIMIT;

		comment.addEventListener('keyup', function(){
				var remaining = LIMIT - this.value.length;
				label.innerHTML = remaining;
				if (remaining < WARNING){
					label.className = 'warning';
				} else {
					label.className = '';
				}
		});
})();

%e7%84%a1%e9%a1%8c

JavaScript パスワード生成

配列からランダムな引数をとるには、Math.floor(Math.random() * xxx.length)のように書きます。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Generator</title>
    <link rel="stylesheet" href="styles.css">
    <style>
      body {
        background: #e0e0e0;
        text-align: center;
        font-family: 'Courier New', sans-serif;
      }
      .container {
        width: 320px;
        margin: 30px auto;
      }
      input[type="text"]{
        width: 300px;
        padding: 7px;
        border-radius: 3px;
        font-size: 24px;
        font-family: 'Courier New', sans-serif;
        text-align: center;
      }
      #btn {
        color: #fff;
        background: #00aaff;
        padding: 7px;
        border-radius: 5px;
        box-shadow: 0 4px 0 #0088cc;
        cursor: pointer;
      }
      #btn:hover {
        opacity: 0.8;
      }
      fieldset {
        margin-top: 40px;
        border: 1px dashed #aaa;
        border-radius: 5px;
        text-align: left;
      }
      legend {
        font-weight: bold;
        padding: 0 10px;
      }
      fieldset p {
        text-align: center;
      }
    </style>
  </head>
  <body>
      <div class="container">
        <p><input type="text" id="result"></p>
        <p><div id="btn">Generate Password</div></p>
        <fieldset>
          <legend>Options</legend>
          <p>Length(<span id="label">8</span>): <input type="range" id="slider" value="8" min="4" max="20"</p>
          <p>
            Numbers?: <input type="checkbox" id="numbers">
            Symbols?: <input type="checkbox" id="symbols">
          </p>
        </fieldset>
        </div>
      <script>

          (function(){
              'use strict'

              var slider = document.getElementById('slider');
              var label = document.getElementById('label');
              var btn = document.getElementById('btn');
              var result = document.getElementById('result');
              var numbers = document.getElementById('numbers');
              var symbols = document.getElementById('symbols');

              function getPassword(){
                var seed_letters = 'abcdefghijklmnopqrstuvwxyz';
                var seed_numbers = '0123456789';
                var seed_symbols = '!#$%&()';
                var seed;
                var len = slider.value;
                var pwd = '';

                seed = seed_letters + seed_letters.toUpperCase();
                if (numbers.checked === true){
                  seed += seed_numbers;
                }
                 if (symbols.checked === true){
                  seed += seed_symbols;
                }

               // for (var i = 0; i < len; i++){
               //   pwd += seed&#91;Math.floor(Math.random() * seed.length)&#93;;
               // }
                while(len--){
                  pwd += seed&#91;Math.floor(Math.random() * seed.length)&#93;;
                }

                result.value = pwd;
              }
              slider.addEventListener('change', function(){
                  label.innerHTML = this.value;
              });
              btn.addEventListener('click', function(){
                  getPassword();
                  // result.value = 'asdfasdf';
              });
              result.addEventListener('click', function(){
                  this.select();
              });

              getPassword();



          })();

      </script>
  </body>
</html>

%e7%84%a1%e9%a1%8c