Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                  <script>
    const questions = [{
      question: 'すきなラーメンは?',
      answers: [{
        text: 'もちろん塩',
        value: 1,
      },
      {
        text: 'もちろん醤油',
        value: 2,
      },
      ],
    },
    {
      question: '好きな動物は?',
      answers: [{
        text: '犬',
        value: 1,
      },
      {
        text: '猫',
        value: 2,
      },
      {
        text: 'どちらでもない',
        value: 3,
      },
      ],
    },
    {
      question: 'すきな山は?',
      answers: [{
        text: '槍ヶ岳!',
        value: 1,
      },
      {
        text: '剣岳',
        value: 2,
      },
      ],
    },
    {
      question: 'すきなお菓子は?',
      answers: [{
        text: 'チョコ',
        value: 1,
      },
      {
        text: 'ケーキ',
        value: 2,
      },
      ],
    },
    ];

    const results = [
      {
        text: 'あなたにおすすめの商品は、Aです! score:',
      },
      {
        text: 'あなたにおすすめの商品は、Bです! score:',
      },
      {
        text: 'あなたにおすすめの商品は、Cです! score:',
      }
    ];

    const showResultText = () => {
      const totalScore = scoreArray.reduce(function (sum, currentValue) {
        return sum + parseInt(currentValue);
      }, 0);
      for (let i = 0; i < results.length; i++) {
        const result = results[i];
        if (totalScore <= 3 && i === 0) {
          scoreElement.innerText = result.text + totalScore;
          break;
        } else if (totalScore < 6 && i === 1) {
          scoreElement.innerText = result.text + totalScore;
          break;
        } else if (i === 2) {
          scoreElement.innerText = result.text + totalScore;
          break;
        }
      }
    }
  </script>
  <div class="container">
    <div id="start" class="start">
      <h1>おすすめ商品診断</h1>
      <button id="start-btn" class="btn">スタート</button>
    </div>
    <div id="quiz" class="quiz hide">
      <div id="question" class="question"></div>
      <div id="answer-buttons" class="answer-buttons"></div>
      <!-- <button id="next-btn" class="btn hide">次へ</button> -->
    </div>
    <div id="result" class="result hide">
      <h1>診断結果</h1>
      <div id="score"></div>
      <p id="result-text" class="result-text"></p>
      <button id="restart-btn" class="btn">もう一度診断する</button>
    </div>
  </div>
              
            
!

CSS

              
                * {
  box-sizing: border-box;
  font-family: sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  align-items: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100vh;
  width: 100vw;
}

.start,
.quiz,
.result {
  align-items: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.btn {
  background-color: #4caf50;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  text-align: center;
  text-decoration: none;
}
button {
  /* background-color: #4caf50; */
  border: none;
  border-radius: 4px;
  color: #333;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  text-align: center;
  text-decoration: none;
  display: block;

}

.btn:hover {
  background-color: #3e8e41;
}

.hide {
  display: none;
}

.question {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 1rem;
}

.answer-btn {
  background-color: #e7e7e7;
  border: none;
  border-radius: 4px;
  color: black;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 0.5rem;
  padding: 0.5rem 1rem;
  text-align: center;
  text-decoration: none;
  width: 100%;
}


              
            
!

JS

              
                const startButton = document.getElementById('start-btn')
// const nextButton = document.getElementById('next-btn')
const restartButton = document.getElementById('restart-btn')
const questionContainer = document.getElementById('quiz')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')
const resultContainer = document.getElementById('result')
const resultText = document.getElementById('result-text')
const scoreElement = document.getElementById('score')
let scoreArray = [];


// !!!!!questionsとresultsの連想配列はそれぞれのページで宣言をする!!!!!!
// さらにshowResultTextの箇所もtotalScoreと結果の数が変動しても使い回せるように、それぞれのページに記述

currentQuestionIndex = 0;
startButton.addEventListener('click', () => {
  startQuiz();
})

function startQuiz() {
  startButton.classList.add('hide')
  resultContainer.classList.add('hide')
  questionContainer.classList.remove('hide')
  showQuestion()
}

function showQuestion() {
  // 連想配列の値をそれぞれ挿入

  // タイトル
  questionElement.innerText = questions[currentQuestionIndex].question;

  // 設問
  questions[currentQuestionIndex].answers.forEach(answer => {
    // ボタンタグを生成して、設問を挿入
    const button = document.createElement('button')
    button.innerText = answer.text;
    const value = answer.value;
    button.dataset.value = value;
    answerButtonsElement.appendChild(button)

    // 選択肢をクリックをする
    button.addEventListener('click', selectAnswer)
  })
}

// 回答の選択
function selectAnswer(e) {
  const selectedButton = e.target;
  // 選択したボタンのvalueを取得
  const scoreData = parseInt(selectedButton.dataset.value);
  // 配列に格納
  scoreArray.push(scoreData);

  if (currentQuestionIndex < questions.length - 1) {
    resetState()
    currentQuestionIndex++
    // console.log(currentQuestionIndex);
    // console.log(scoreArray)
    // nextButton.classList.remove('hide');
    showQuestion()
  } else {
    showResult();
  }
}

function resetState() {
  // https://into-the-program.com/removechild/
  // これで子要素をすべて削除
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

// 結果の表示
function showResult() {

  console.log(scoreArray)

  questionContainer.classList.add('hide');
  resultContainer.classList.remove('hide');

  // 下記のコメントアウトの部分をshowResuktText()として、それぞれのページで記述する
  // 配列の数値を合算。
  // const totalScore = scoreArray.reduce(function (sum, currentValue) {
  //   return sum + parseInt(currentValue);
  // }, 0);
  // for (let i = 0; i < results.length; i++) {
  //   const result = results[i];
  //   if (totalScore <= 3 && i === 0) {
  //     scoreElement.innerText = result.text + totalScore;
  //     break;
  //   } else if (totalScore < 6 && i === 1) {
  //     scoreElement.innerText = result.text + totalScore;
  //     break;
  //   } else if (i === 2) {
  //     scoreElement.innerText = result.text + totalScore;
  //     break;
  //   }
  // }

  // showResultTextのfunctionを、それぞれのhtmlの箇所で記述をする。
  showResultText();
}


// もう一度診断するのボタンをクリック
restartButton.addEventListener('click', () => {
  resultContainer.classList.add('hide')
  startButton.classList.remove('hide')
  currentQuestionIndex = 0;
  scoreArray = [];
  resetState()
})
              
            
!
999px

Console