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

Javascript おみくじ

<!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;
        text-align: center;
        font-size: 16px;
        color: #fff;
        font-family: Arial, sans-serif;
      }
      #result {
        margin: 30px auto;
        width: 180px;
        height: 180px;
        border-radius: 50%;
        line-height: 180px;
        font-size: 48px;
        font-weight: bold;
        background: #f44336;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
      }
      #btn {
        margin: 0 auto;
        width: 200px;
        padding: 5px;
        border-radius: 5px;
        background: #00aaff;
        box-shadow: 0 4px 0 #0088cc;
        cursor: pointer;
      }
      #btn:hover{
        opacity: 0.8;
      }
      #btn.pushed{
        margin-top: 32px;
        box-shadow: 0 2px 0 #0088cc;
      }
    </style>
  </head>
  <body>
      <div id="result">?</div>
      <div id="btn">あなたの運勢は?</div>
      <script>
        (function(){
          "use strict";
          document.getElementById('btn').addEventListener('click', function(){
            var results = ['大吉','中吉','小吉','凶'];
            var result = Math.floor(Math.random() * results.length);
            document.getElementById('result').innerHTML = results[result];
          });
          document.getElementById('btn').addEventListener('mousedown', function(){
            this.className = 'pushed';
          });
          document.getElementById('btn').addEventListener('mouseup', function(){
            this.className = '';
          });
        })();
      </script>
  </body>
</html>

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

JavaScript 基礎

JavaScriptのドキュメントはMDNのサイトでよく参照することができます。
MDN JavaScript

即時関数:直ぐに実行されます。

<script>
       (function(name){
        console.log("hello" + name);
      })("tom");
      </script>
      <script>
      (function()){
        var x = 10;
        y = 20;
        console.log(x + y);
      }();
      </script>

setInterval

var i = 0;
      function show(){
        console.log(i++)
      }
      setInterval(function(){
        show();
      }, 1000);

setTimeout

var i = 0;
      function show(){
        console.log(i++);
        setTimeout(function(){
          show();
        }, 1000);
      }show();

オブジェクト

var user = {
        email: "yamada@gmail.com",
        score: 80
      };
      console.log(user.email)

オブジェクト2

var user = {
        email: "yamada@gmail.com",
        score: 80,
        greet: function(name){
          console.log("hello, " + name);
        }
      };
      user.greet("sato");

Arrayオブジェクト

var a = new Array(100, 300, 200);
      console.log(a.length);

Math

      console.log(Math.PI);
      console.log(Math.ceil(5.3));
      console.log(Math.floor(5.3));
      console.log(Math.round(5.3));

三項演算子
a = (条件) ? b : c;

よく使うもの

console.log(window.outerHeight);
window.location.href = "http://google.com"
document(DOM)
var e = document.getElementById('msg');
      e.textContent = 'Hello';
      e.style.color = 'red';

CSS メディアクエリによるレスポンシブル対応

h1, h2, p, img, ul{
	margin:0;
}

body {
	font-family: Arial, Verdana, sans-serif;
	margin:0 auto;
	width: 95%;

}

#header {
	background: red;
}

#footer {
	background: green;
}

#container {
}

#main {
	background: orange;
}

#sub {
	background: yellow;
}

#footerNavLink{
	float: right;
}

#headerNav ul {
	list-style: none;
	overflow: hidden;
}

#headerNav li {
	float: left;
	width: 33%;
	text-align: center;
}

img {
	max-width: 100%;
}

.movie {
	position: relative;
	height: 0;
	padding-top: 56.25%;
}

iframe {
	height: 100%;
	position: absolute;
	left:0;
	top:0;
	width:100%;
}

/* スマホ */
#headerNav{
	display: none;
}

/* タブレット */
@media screen and (min-width: 480px){
	#footerNavLink {
		display: none;
	}
	#headerNav{
		display: block;
	}
	#footerNav {
		display: none;
	}

}

/* PC */
@media screen and (min-width: 768px){
	#container {
		overflow: hidden;
	} 
	#main {
		float: left;
		width: 78.0612245%;
	}
	#sub {
		float: right;
		width: 20.4081633%;
	}
}

Bootstrap tooltip, popover

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Bootstrap Practice</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

    <div class="container" style="padding:20px 0">

      <p><a href="#" data-toggle="tooltip" title="説明">this</a> and <a href="#" data-toggle="popover" title="説明" data-content="さらに説明">that</a>.</p>

    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script>
      $(function(){
        $("[data-toggle=tooltip]").tooltip({
          placement: 'bottom'
        });
        $("[data-toggle=popover]").popover();
      });
    </script>
  </body>
</html>

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

Bootstrap クリッカブルタブメニュー

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Bootstrap Practice</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

    <div class="container" style="padding:20px 0">

      <ul class="nav nav-tabs" style="margin-bottom:15px">
      <li class="active"><a href="#home" data-toggle="tab">Home</a></li>
      <li><a href="#about" data-toggle="tab">About</a></li>
      </ul>

      <div class="tab-content">
        <div class="tab-pane active" id="home">ほーむだよ</div>
        <div class="tab-pane" id="about">aboutだよ</div>
      </div>

    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

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

Bootstrap modalウィンドウ

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Bootstrap Practice</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

    <div class="container" style="padding:20px 0">

    <a data-toggle="modal" href="#myModal" class="btn btn-primary">show me</a>

    <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">my modal</h4>
        </div>
        <div class="modal-body">
        こんにちは!
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary">OK!</button>
        </div>
      </div>
    </div>

    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

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

Bootstrap progress-bar

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Bootstrap Practice</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

    <div class="container" style="padding:20px 0">

    <div class="progress">
        <div class="progress-bar progress-bar-primary" style="width:60%"></div>
    </div>

     <div class="progress progress-striped active">
        <div class="progress-bar progress-bar-info" style="width:60%"></div>
    </div>

    <div class="progress progress-striped active">
        <div class="progress-bar progress-bar-info" style="width:30%"></div>
        <div class="progress-bar progress-bar-primary" style="width:20%"></div>
        <div class="progress-bar progress-bar-warning" style="width:10%"></div>
    </div>

    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

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