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

JavaScript 割り勘電卓

Math.floorは切り捨て、Math.ceilは切り上げ、Math.absは絶対値という仕組みを上手く利用します。正規関数/^[1-9][0-9]*$/も使用します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>割り勘電卓</title>
    <link rel="stylesheet" href="styles.css">
    <style>
      body {
        font-size:16px;
        text-align: center;
        font-family: Arial, sans-serif;
      }
      h1 {
        font-size: 24px;
      }
      input[type="text"]{
        padding: 7px;
        border: 1px solid #ddd;
        border-radius: 3px;
        width: 100px;
        font-weight: bold;
        font-size: 18px;
        text-align: right;
      }
      #btn {
        margin: 30px auto;
        width: 180px;
        border-radius: 5px;
        box-shadow: 0 4px 0 #e91b0c;
        background: #f44336;
        color: #fff;
        cursor: pointer;
        padding: 7px;
      }
      #btn:hover{
        opacity: 0.8;
      }
    </style>
  </head>
  <body>
      <h1>割り勘電卓</h1>
      <p>金額 <input type="text" id="price" value="0">
      <p>人数 <input type="text" id="num" value="0">
      <div id="btn">計算する</div>
      <p id="result"></p>
      <script>
      (function(){
          'use strict';

          var priceForm = document.getElementById('price');
          var numForm = document.getElementById('num');
          var btn = document.getElementById('btn');
          var result = document.getElementById('result');

          priceForm.addEventListener('click', function(){
              this.select();
          });
          numForm.addEventListener('click', function(){
              this.select();
          });

          btn.addEventListener('click', function(){
              var price = priceForm.value;
              var num = numForm.value;
              var x1, x2, y1, y2;
              var unit = 100;

              if (price.match(/^[1-9][0-9]*$/) && num.match(/^[1-9][0-9]*$/)){
                  if (price % num === 0){
                    result.innerHTML = '一人' +(price / num)+'円丁度です!';
                  } else {
                    x1 = Math.floor(price / num / unit) * unit;
                    y1 = price - (x1 * num);
                    x2 = Math.ceil(price / num / unit) * unit;
                    y2 = Math.abs(price - (x2 * num));
                    result.innerHTML = 
                    '一人' + x1 + '円だと' + y1 + '円足りません。<br>' +
                    '一人' + x2 + '円だと' + y2 + '円余ります。';
                  }
              } else {
                result.innerHTML = '入力された値に誤りがあります。'
              }
          });
      })();
      </script>
  </body>
</html>

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

JavaScript 秒数当てゲーム

秒数当てゲームもストップウォッチのように、(Date.now()- startTime) / 1000 と記載していきます。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>stop at 00:05!</title>
    <link rel="stylesheet" href="styles.css">
    <style>
    body {
      background: #e0e0e0;
      text-align: center;
      font-size: 16px;
      font-family: Arial, san-serif;
    }
    #result {
      font-weight: bold;
      font-size: 32px;
      margin: 60px auto;
      color: #00aaff;
      text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
    }
    #btn {
      margin: 0 auto;
      width: 200px;
      padding: 7px;
      color: #fff;
      border-radius: 5px;
      background: #00aaff;
      box-shadow: 0 4px 0 #0088cc;
      cursor: pointer;
    }
    #btn:hover {
      opacity: 0.8;
    }
    </style>
  </head>
  <body>
      <div id="result"></div>
      <div id="btn">START</div>
      <script>
      (function(){
        'use strict';
        var isStarted = false;
        var startTime;
        var diff;
        var msg = 'Stop at 00:05!'

        var result = document.getElementById('result');
        var btn = document.getElementById('btn');

        result.innerHTML = msg;

        btn.addEventListener('click', function(){
            if (!isStarted){
              isStarted = true;
              this.innerHTML = 'STOP';
              startTime = Date.now();
              result.innerHTML = msg;
            } else {
              isStarted = false;
              this.innerHTML = 'START';
              diff = (Date.now()- startTime) / 1000 -5;
              if (diff >= -0.1 && diff <= 0.1){
                result.innerHTML = 'Perfect!';
              } else if (diff > 0){
                result.innerHTML = 'You are ' + diff.toFixed(2) + 'seconds late!';
              } else {
                result.innerHTML = 'You are ' + Math.abs(diff).toFixed(2) + 'seconds first!';
              }
            }
        });
      })();
      </script>
  </body>
</html>

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

JavaScript ストップウォッチ

ストップウォッチは、Date関数を上手く活用して、クリックしたタイミングの差分を表示します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ストップウォッチ</title>
    <link rel="stylesheet" href="styles.css">
    <style>
    body {
      background: #e0e0e0;
      font-family: Arial, sans-serif;
      text-align: center;
    }
    #timerText{
      color: #00aaff;
      font-size: 128px;
      margin: 40px auto;
      text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
    }
    .btn{
      display: inline-block;
      width: 100px;
      padding: 7px;
      border-radius: 5px;
      box-shadow: 0 4px 0 #0088cc;
      color: #fff;
      background: #00aaff;
      cursor: pointer;
    }
    .btn + .btn {
      margin-left:10px;
    }
    .btn.active {
      opacity: 1.0;
    }
    .btn.inactive {
      opacity: 0.5;
    }
    </style>
  </head>
  <body>
      <div id="timerText">0.00</div>
      <div id="start">START</div>
      <div id="stop">STOP</div>
      <div id="reset">RESET</div>
      <script>
        (function(){
          'use strict';

          var startTime;
          var timerId;
          var elapsedTime = 0;
          var isRunning = false;

          var startButton = document.getElementById('start');
          var stopButton = document.getElementById('stop');
          var resetButton = document.getElementById('reset');
          var timerText = document.getElementById('timerText');

          function setButtonState(start, stop, reset){
            startButton.className = start ? 'btn active' : 'btn inactive';
            stopButton.className = stop ? 'btn active' : 'btn inactive';
            resetButton.className = reset ? 'btn active' : 'btn inactive';
          }

          setButtonState(true, false, false);

          startButton.addEventListener('click', function(){
            if (isRunning) return;
            isRunning = true;
                startTime = Date.now();
                updateTimerText();
                setButtonState(false, true, false);
          });

          stopButton.addEventListener('click', function(){
            if (!isRunning) return;
            isRunning = false;
            elapsedTime += Date.now()- startTime;
            clearTimeout(timerId);
            setButtonState(true, false, true);
          });

          resetButton.addEventListener('click', function(){
            if (isRunning) return;
            timerText.innerHTML = '0.00';
            elapsedTime = 0;
            setButtonState(true, false, false);
          });

          function updateTimerText(){
            timerId = setTimeout(function(){
                var t = Date.now() - startTime + elapsedTime;
                timerText.innerHTML = (t / 1000).toFixed(2);
                updateTimerText();
            }, 10);
          }

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

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