こんにちは。KOUKIです。
本記事は、Udemyの「50 Projects In 50 Days – HTML, CSS & JavaScript」で学習したことを載せています。
<目次>
実装するもの
今回は、「パスワードジェネレータ機能」をJavaScriptで実装したいと思います。
demoは「こちら」で確認できます。
環境構築
簡単な環境構築をお願いします。
必要なファイルは、以下の通りです。
1 2 3 4 5 6 |
$ tree . ├── index.html ├── script.js └── style.css |
CSS版
ページ(HTML)の作成
最初にページを作成しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" /> <link rel="stylesheet" href="style.css" /> <title>Password Generator</title> </head> <body> <div class="container"> <h2>Password Generator</h2> <div class="result-container"> <span id="result"></span> <button class="btn" id="clipboard"> <i class="far fa-clipboard"></i> </button> </div> <div class="settings"> <div class="setting"> <label>Password Length</label> <input type="number" id="length" min="4" max="20" value="20"> </div> <div class="setting"> <label>Include uppercase letters</label> <input type="checkbox" id="uppercase" checked> </div> <div class="setting"> <label>Include lowercase letters</label> <input type="checkbox" id="lowercase" checked> </div> <div class="setting"> <label>Include numbers</label> <input type="checkbox" id="numbers" checked> </div> <div class="setting"> <label>Include symbols</label> <input type="checkbox" id="symbols" checked> </div> </div> <button class="btn btn-large" id="generate"> Generate Password </button> </div> <script src="script.js"></script> </body> </html> |
このHTMLをブラウザ上で表示すると以下のようになります。

スタイル(CSS)を装飾
次にスタイルを記述しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap'); * { box-sizing: border-box; } body { background-color: #3b3b98; color: #fff; font-family: 'Muli', sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; padding: 10px; margin: 0; } h2 { margin: 10px 0 20px; text-align: center; } .container { background-color: #23235b; box-shadow: 0px 2px 10px rgba(255, 255, 255, 0.2); padding: 20px; width: 350px; max-width: 100%; } .result-container { background-color: rgba(0, 0, 0, 0.4); display: flex; justify-content: flex-start; align-items: center; position: relative; font-size: 18px; letter-spacing: 1px; padding: 12px 10px; height: 50px; width: 100%; } .result-container #result { word-wrap: break-word; max-width: calc(100% - 40px); } .result-container .btn { position: absolute; top: 5px; right: 5px; width: 40px; height: 40px; font-size: 20px; } .btn { border: none; background-color: #3b3b98; color: #fff; font-size: 16px; padding: 8px 12px; cursor: pointer; } .btn-large { display: block; width: 100%; } .setting { display: flex; justify-content: space-between; align-items: center; margin: 15px 0; } |
ここまで実装すると以下のようになります。

JavaScriptの実装
パスワードジェネレータには、以下の3つの機能があります。
2: パスワード生成機能
3: クリップボードコピー機能
ランダム文字列生成機能
パスワードジェネレータにはランダムな文字列が必須なので、まずはそれを実装しましょう。
関数の定義
ランダム文字列は、JavaScriptのStringオブジェクトで作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// ランダムの小文字を返す function getRandomLower() { return String.fromCharCode(Math.floor(Math.random() * 26) + 97) } // ランダムの大文字を返す function getRandomUpper() { return String.fromCharCode(Math.floor(Math.random() * 26) + 65) } // ランダムの数字を返す function getRandomNumber() { return String.fromCharCode(Math.floor(Math.random() * 10) + 48) } // ランダムのシンボルを返す function getRandomSymbol() { const symbols = '!@#$%^&*(){}[]=<>/,.' return symbols[Math.floor(Math.random() * symbols.length)] } |
上記の関数では、String.fromCharCodeメソッドを使用しています。これは、与えられたコードから特定の文字列を生成するためのものです。
コードについては、Differences Between Character Setsに一覧があるので、確認してみてください。
オブジェクトの作成
作成した関数は、JavaScriptのオブジェクトに格納しておきましょう。
1 2 3 4 5 6 7 8 9 10 |
// randomFuncオブジェクトに格納 const randomFunc = { lower: getRandomLower, upper: getRandomUpper, number: getRandomNumber, symbol: getRandomSymbol } // ランダムの小文字を返す ... |
パスワード生成機能
次は、パスワード生成機能を作成します。
要素の取得
画面操作に必要な要素を取得しましょう。
1 2 3 4 5 6 7 8 9 10 11 |
// 要素を取得する const resultEl = document.getElementById('result') const lengthEl = document.getElementById('length') const uppercaseEl = document.getElementById('uppercase') const lowercaseEl = document.getElementById('lowercase') const numbersEl = document.getElementById('numbers') const symbolsEl = document.getElementById('symbols') const generateEl = document.getElementById('generate') const clipboardEl = document.getElementById('clipboard') // randomFuncオブジェクトに格納 |
クリックイベントの登録
クリックイベントを登録して、「Generate Password」ボタンが押下された時にイベントが発火するようにしましょう。
1 2 3 4 5 6 7 8 9 10 11 |
// クリックイベントの登録 generateEl.addEventListener('click', () => { const length = +lengthEl.value const hasLower = lowercaseEl.checked const hasUpper = uppercaseEl.checked const hasNumber = numbersEl.checked const hasSymbol = symbolsEl.checked resultEl.innerText = generatePassword( hasLower, hasUpper, hasNumber, hasSymbol, length) }) |
generatePassword関数はまだ作成していないので動きませんが、これで画面のチェックボックスの状態やパスワードの指定長によって、生成されるパスワードを制御できるようになります。
そして、generatePasswordの実行結果が、resultEl.innerTextにより画面に表示されます。
パスワードの生成
次は、パスワードの生成処理を作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// パスワードの生成 function generatePassword(lower, upper, number, symbol, length) { // 初期化 let generatedPassword = '' // 0 ~ 4の値が入る // (true + true + true + true => 4とjavascriptでは計算される) const typesCount = lower + upper + number + symbol // 変数名をKeyにしたオブジェクトを作成[{lower: true}, {upper: true}...] const typesArr = [{lower}, {upper}, {number}, {symbol}] .filter(item => Object.values(item)[0]) if(typesCount === 0) { return '' } for(let i = 0; i < length; i += typesCount) { typesArr.forEach(type => { // Object.keys() メソッドでKeyを取り出す // https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/keys const funcName = Object.keys(type)[0] generatedPassword += randomFunc[funcName]() }) } // 指定文字長でカット const finalPassword = generatedPassword.slice(0, length) return finalPassword } |
ここは、少し難しいかもしれません。特に以下の処理が難しいですね。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// JavaScriptの不可解な計算 > true + true 2 // 変数名をKeyにしたオブジェクトを作る大技 var lower = true var upper = true var number = true var symbol = true [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]) (4) [{…}, {…}, {…}, {…}] 0: {lower: true} 1: {upper: true} 2: {number: true} 3: {symbol: true} length: 4 __proto__: Array(0) |
randomFuncは、文字列生成関数をオブジェクト化した変数です。typesArrには関数名をKeyにしたオブジェクトが格納されているので、そのKeyをObject.keysで取得し、関数として実行することでパスワードが生成されます。
クリップボードコピー機能
最後にクリップボードコピー機能を作って、完成です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// クリップボードにコピー clipboardEl.addEventListener('click', () => { const textarea = document.createElement('textarea') const password = resultEl.innerText if(!password) { return } textarea.value = password document.body.appendChild(textarea) textarea.select() document.execCommand('copy') textarea.remove() alert('Password copied to clipboard!') }) |
クリップボードのコピーでは、最初にtextareaを作成し、そこに生成したパスワードを追加して、documentのbodyの子要素とします。
そして、textarea.selectでコピーした要素を選択後、document.execCommand(‘copy’)でクリップボードにコピーしています。
textarea.removeは、bodyに追加したtextareaを削除しています。
document.execCommandは廃止されたため非推奨のようですが、私のChromeでは動きました。もしかしたら、将来動かなくなるのかもしれませんね。

おわりに
ランダム文字列を生成するString.fromCharCodeメソッド、変数名をKeyにする大技、「true + true => 2」になるJavaScriptの謎の計算など、結構勉強になることが多かったですね^^
この機能も他のアプリに応用ができそうなので、覚えておいて損はないと思います!
それでは、また!
JavaScriptまとめ
JavaScript ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
// 要素を取得する const resultEl = document.getElementById('result') const lengthEl = document.getElementById('length') const uppercaseEl = document.getElementById('uppercase') const lowercaseEl = document.getElementById('lowercase') const numbersEl = document.getElementById('numbers') const symbolsEl = document.getElementById('symbols') const generateEl = document.getElementById('generate') const clipboardEl = document.getElementById('clipboard') // randomFuncオブジェクトに格納 const randomFunc = { lower: getRandomLower, upper: getRandomUpper, number: getRandomNumber, symbol: getRandomSymbol } // クリップボードにコピー clipboardEl.addEventListener('click', () => { const textarea = document.createElement('textarea') const password = resultEl.innerText if(!password) { return } textarea.value = password document.body.appendChild(textarea) textarea.select() document.execCommand('copy') textarea.remove() alert('Password copied to clipboard!') }) // クリックイベントの登録 generateEl.addEventListener('click', () => { const length = +lengthEl.value const hasLower = lowercaseEl.checked const hasUpper = uppercaseEl.checked const hasNumber = numbersEl.checked const hasSymbol = symbolsEl.checked resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, length) }) // パスワードの生成 function generatePassword(lower, upper, number, symbol, length) { // 初期化 let generatedPassword = '' // 0 ~ 4の値が入る // (true + true + true + true => 4とjavascriptでは計算される) const typesCount = lower + upper + number + symbol // 変数名をKeyにしたオブジェクトを作成[{lower: true}, {upper: true}...] const typesArr = [{lower}, {upper}, {number}, {symbol}] .filter(item => Object.values(item)[0]) if(typesCount === 0) { return '' } for(let i = 0; i < length; i += typesCount) { typesArr.forEach(type => { // Object.keys() メソッドでKeyを取り出す // https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/keys const funcName = Object.keys(type)[0] generatedPassword += randomFunc[funcName]() }) } // 指定文字長でカット const finalPassword = generatedPassword.slice(0, length) return finalPassword } // ランダムの小文字を返す function getRandomLower() { return String.fromCharCode(Math.floor(Math.random() * 26) + 97) } // ランダムの大文字を返す function getRandomUpper() { return String.fromCharCode(Math.floor(Math.random() * 26) + 65) } // ランダムの数字を返す function getRandomNumber() { return String.fromCharCode(Math.floor(Math.random() * 10) + 48) } // ランダムのシンボルを返す function getRandomSymbol() { const symbols = '!@#$%^&*(){}[]=<>/,.' return symbols[Math.floor(Math.random() * symbols.length)] } |
コメントを残す
コメントを投稿するにはログインしてください。