フロントエンジニアになるための練習問題 押すと色が変わるボタン5
前回の課題の続きです。
課題
前回、ボタンをクリックすると5秒間はクリックしても色が変わらないようにしましたが、それをユーザーがわかるように実装して欲しいと追加の依頼をもらいました。
- ボタンをクリックしても色が変化しない期間中は、ボタンという文字を処理中…に変更してほしい
前提
- javascriptを使って、テキストを動的に変更できる
30分程度。
実装の流れ
- クリックされた時にテキストを「処理中…」に変更する
- 5秒経過後の処理でテキストを「ボタン」に変更する
実装例
シンプルに innerText でボタンのテキストを変更しました。// 追加 と書かれている二行を追加しただけです。
const getRandom = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const getClass = (value) => {
switch (value) {
case 1: {
return 'red-active';
}
case 2: {
return 'blue-active';
}
case 3: {
return 'yellow-active';
}
}
};
let canClick = true;
const startButtonEl = document.getElementById("start-button");
startButtonEl.addEventListener("click", () => {
if(!canClick) return;
canClick = false;
startButtonEl.innerText = '処理中...'; //追加
setTimeout(() => {
canClick = true;
startButtonEl.innerText = 'ボタン'; //追加
}, 5000);
if(startButtonEl.classList.contains("red-active") || startButtonEl.classList.contains("blue-active") || startButtonEl.classList.contains("yellow-active")){
startButtonEl.classList.remove("red-active", "blue-active", "yellow-active");
}else{
const value = getRandom(1, 3);
const applyClass = getClass(value);
startButtonEl.classList.add(applyClass);
}
});
最近のコメント