フロントエンドデベロッパーのメモ

スキル: HTML/Jade/Jinja2, CSS/SCSS, JavaScript(ES6), Angular, React,Next, Redux, Node, Express, Python, Flask, Postgres, Redis, MongoDB, Kafka, Knex, SQLAlchemy, React Native, EXPO, GraphQL/Apollo, REST, AWS, Heroku, Docker, CircleCI, SCRUM, XP, Vim, TDD

Cookieにブラウザの表示回数をセットしてみた。

以前にCookieを使って簡単なゲームを作ってみたのでここにコードを残しておきます。 本当はPlunkerとかに保存できたらと思ったんですが、画像を保存したりサブフォルダ作ったりできなかったので諦めました。 このゲームを作った時の条件は以下の通りです。

  • ユーザーは風船とページの訪問回数をみることができる。

  • 風船の色は赤と青の二色がある。

  • ユーザーが初めてページを開いた時は、50:50の確率でランダムで風船の色が選択される。

  • 二回目以降は、前に選択された風船と同じ色を表示する。

  • 表示回数と風船の色についての情報はlocalStrageを使わずにcookieに書き込む。

package.json

{
  "name": "balloon",
  "version": "1.0.0",
  "main": "server.js",
  "license": "MIT",
  "scripts": {
    "start": "nodemon node server.js",
    "test": "mocha"
  },
  "dependencies": {
    "express": "^4.16.3",
    "nodemon": "^1.18.3",
    "path": "^0.12.7"
  }
}

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Welcome!!</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="report">
        <p id="color"></p>
        <p id="times"></p>
    </div>
    <div id="remove">
        <span id="remove-message">Click & Remove your Cookie</span>
    </div>
    <div class="balloons"></div>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
    <script type="text/javascript" src="./app.js"></script>
</body>

</html>

style.css

body {
  display: flex;
}

#report {
  display: flex;
  width: 100%;
  height: 50px;
  border: 5px solid #333;
  border-radius: 5px;
  justify-content: center;
  align-items: center;
  z-index: 1;
}

p {
  text-align: center;
  font-size: 50px;
}

#remove {
  position: fixed;
  height: 100px;
  width: 100px;
  right: 10px;
  bottom: 110px;
  border: solid 5px green;
  border-radius: 50%;
  background: green;
}

#remove-message {
  position: absolute;
  top: 25%;
  color: #fff;
}

.balloons {
  position: fixed;
  width: 100%;
  height: 250px;
  -webkit-animation: moveup 5s linear;
  animation: moveup 5s linear;
  opacity: 0;
}

@-webkit-keyframes moveup {
  0% {
    bottom: 0%;
    opacity: 1;
  }
  100% {
    bottom: 100%;
    opacity: 0;
  }
}
@keyframes moveup {
  0% {
    bottom: 0%;
    opacity: 1;
  }
  100% {
    bottom: 100%;
    opacity: 0;
  }
}

server.js

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(__dirname + "/"));
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "./index.html")));
app.listen(3000, () => console.log("Listening on port 3000!"));

app.js

/**
 * Initialise a function to render a balloon and report
 */
function init() {
  // get a cookie information
  let cookie = decodeURIComponent(document.cookie);
  // if a user does not have a cookie set cookie with chosen balloon color
  if (cookie.length === 0) {
    // judge the initial value with a random value to select a balloon color
    const val = Math.random();
    let balllonColor = chooseBalloon(val);
    // set user information in cookie with the following information
    // the balloon color, the number of times user opened the page
    setCookie("color", balllonColor);
    setCookie("times", 1);
    // record how many times a user has seen each color of ball
    // provide a report on users and number of times they saw each color ball
    setTextInReport(balllonColor, 1);
    renderBalloon(balllonColor);
  } else {
    // get a cookie and,
    //  the next time a user visits the page show the same color ball they saw previously
    const balllonColor = Cookies.get("color");
    let times = parseInt(Cookies.get("times"));
    times += 1;
    setCookie("times", times);
    setTextInReport(balllonColor, times);
    renderBalloon(balllonColor);
  }
  // remove a cookie
  const removebtn = document.getElementById("remove");
  removebtn.addEventListener("click", removeCookie);
}

/**
 * Render a balloon with a given color
 * @param {String} color
 */
function renderBalloon(color) {
  // get balloon id
  const balloon = document.querySelector("div.balloons");
  // balloon color path
  const bcp = color === "red" ? "./images/red.jpeg" : "./images/blue.jpeg";
  let i = 1;
  while (i < 13) {
    const img = document.createElement("img");
    img.setAttribute("src", bcp);
    img.setAttribute("width", "304");
    img.setAttribute("height", "228");
    balloon.appendChild(img);
    i++;
  }
}

/**
 * Choose a Balloon color
 * @param {Number} num
 */
function chooseBalloon(num) {
  let color = "";
  // if the val is bigger than 0.5, then a user will see a red balloon image
  // otherwise a user will see a blue balooon image
  color = num >= 0.5 ? "red" : "blue";
  return color;
}

/**
 * Set a cookie
 * @param {String} name
 * @param {Number} val
 */
function setCookie(name, val) {
  Cookies.set(name, val, { expires: 7, path: "" });
}

/**
 *  Set texts in a report
 * @param {String} color
 * @param {Number} nums
 */
function setTextInReport(color, nums) {
  const ucolor = document.getElementById("color");
  const unums = document.getElementById("times");
  ucolor.style.color = color === "blue" ? "blue" : "red";
  ucolor.innerHTML = `This is your color, ${color}!`;
  unums.innerHTML = `You visited this page ${nums}!!`;
}

/**
 * Remove cookie
 */
function removeCookie() {
  Cookies.remove("color");
  Cookies.remove("times");
}

// Trigger the init function
init();

gif画像載せようとしましたけど、ブログサイトのメモリ容量的に厳しいみたいなのでありません。 上記のコードをコピペして、風船の画像をimagesディレクトリに保存して、yarn (or npm install)後のyarn start or(npm run start)したら http://localhost:3000/ で雰囲気が伝わると思うので興味がある方は試してみてください。