A Simple jQuery Quiz App

A Simple jQuery Quiz App
Code Snippet:"What Type Of Thing Are You" Quiz with jQuery
Author: jan dennison
Published: January 12, 2024
Last Updated: January 22, 2024
Downloads: 428
License: MIT
Edit Code online: View on CodePen
Read More

This code creates a simple jQuery quiz app. It generates quiz questions with multiple answers and calculates a total score based on the selected options. The app then matches the score to predefined results, displaying a final outcome. It helps create interactive quizzes to assess users’ preferences.

You can integrate this quiz app into your blog, website, or educational platform to engage users interactively.

How to Create a Simple Quiz App Using jQuery

1. Create the HTML structure as follows. Modify the content within the <ul> elements to create your quiz questions and answer options.

<div id="quizzie">
  <h1>What Type Of Thing Are You?</h1>
    <ul class="quiz-step step1 current">
        <li class="question">
            <div class="question-wrap">
                <h2>Question #1: Are you more...</h2>
            </div>
        </li>
        <li class="quiz-answer low-value" data-quizIndex="2">
            <div class="answer-wrap"> 
                <p class="answer-text">This Thing</p>
            </div>
        </li>
        <li class="quiz-answer high-value" data-quizIndex="4">
            <div class="answer-wrap"> 
                <p class="answer-text">That Thing</p>
            </div>
        </li>
    </ul>
    <ul class="quiz-step step2">
        <li class="question">
            <div class="question-wrap">
                <p>Question #2: Are you more...</p>
            </div>
        </li>
        <li class="quiz-answer low-value" data-quizIndex="2">
            <div class="answer-wrap"> 
                <p class="answer-text">First Thing</p>
            </div>
        </li>
        <li class="quiz-answer high-value" data-quizIndex="4">
            <div class="answer-wrap">
                <p class="answer-text">Second Thing</p>
            </div>
        </li>
    </ul>
    <ul class="quiz-step step3">
        <li class="question">
            <div class="question-wrap">
                <p>Question #3: Are you more...</p>
            </div>
        </li>
        <li class="quiz-answer low-value" data-quizIndex="2">
            <div class="answer-wrap">
                <p class="answer-text">One Thing</p>
            </div>
        </li>
        <li class="quiz-answer high-value" data-quizIndex="4">
            <div class="answer-wrap">
                <p class="answer-text">Another Thing</p>
            </div>
        </li>
    </ul>
    <ul class="quiz-step step4">
        <li class="question">
            <div class="question-wrap">
                <p>Question #4: Are you more...</p>
            </div>
        </li>
        <li class="quiz-answer low-value" data-quizIndex="2">
            <div class="answer-wrap">
                <p class="answer-text">Thing 1</p>
            </div>
        </li>
        <li class="quiz-answer high-value" data-quizIndex="4">
            <div class="answer-wrap">
                <p class="answer-text">Thing 2</p>
            </div>
        </li>
    </ul>
    <ul id="results">
        <li class="results-inner">
            <p>Your result is:</p>
            <h1></h1>
            <p class="desc"></p>
        </li>
    </ul>
</div>

2. Adjust the styling in the CSS code to match your website’s design.

@import url(https://fonts.googleapis.com/css?family=Satisfy|Pathway+Gothic+One);
/* Defaults */
html, body, #quizzie {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

* {
  box-sizing: border-box;
}

body {
  background: #677c8a;
  color: #fff;
}

h1 {
  font-family: 'Satisfy', 'cursive';
  font-size: 2.5em;
}

h2, p {
  font-family: 'Pathway Gothic One', 'sans-serif';
  font-size: 2em;
}

h1, h2, p {
  text-align: center;
  display: block;
  width: auto;
  margin: 1%;
}

#quizzie {
  padding: 5% 0;
  /* Individual Steps/Sections */
  /* Content */
}
#quizzie ul {
  list-style: none;
  display: block;
  width: auto;
  margin: 2% 2%;
  padding: 2%;
  overflow: auto;
  display: none;
  /* Step Questions and Answer Options */
}
#quizzie ul.current {
  display: block;
}
#quizzie ul li {
  display: inline-block;
  float: left;
  width: 49%;
  margin-right: 2%;
  overflow: auto;
  text-align: center;
}
#quizzie ul li.quiz-answer {
  cursor: pointer;
}
#quizzie ul li.question, #quizzie ul li.results-inner {
  display: block;
  float: none;
  width: 100%;
  text-align: center;
  margin: 0;
  margin-bottom: 2%;
}
#quizzie ul li.results-inner {
  padding: 5% 2%;
}
#quizzie ul li.results-inner img {
  width: 250px;
}
#quizzie ul li:last-child {
  margin-right: 0;
}
#quizzie .question-wrap, #quizzie .answer-wrap {
  display: block;
  padding: 1%;
  margin: 1em 10%;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
}
#quizzie .answer-wrap {
  background: Turquoise;
  -moz-transition: background-color 0.5s ease;
  -o-transition: background-color 0.5s ease;
  -webkit-transition: background-color 0.5s ease;
  transition: background-color 0.5s ease;
}
#quizzie .answer-wrap:hover {
  background: DarkTurquoise;
}

3. Now, load the jQuery JavaScript library by adding the following scripts before closing the body tag:

  <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

4. Finally, add the following JavaScript code to your project. Customize the resultOptions array in the JavaScript code with your result titles and corresponding descriptions. Replace the image URLs in the desc property with images relevant to each result.

// Quiz result options in a separate object for flexibility
var resultOptions = [
    {   title: 'You Are This Thing',
        desc: '<p>Here, have an Archer</p><img src="https://i.imgur.com/tXTjD9k.jpg"/>'},
    {   title: 'You Are That Thing',
        desc: '<p>Here, have an Archer</p><img src="https://i.imgur.com/dipkE0v.jpg"/>'},
    {   title: 'You Are This Other Thing',
        desc: '<p>Here, have an Archer</p><img src="https://i.imgur.com/WXox0Yv.jpg"/>'},
    {   title: 'You Are This One Thing',
        desc: '<p>Here, have an Archer</p><img src="https://i.imgur.com/NH5cunw.png"/>'},
    {   title: 'You Are A Type Of Thing',
        desc: '<p>Here, have an Archer</p><img src="https://i.imgur.com/NH5cunw.png"/>'}
];
    
// global variables
var quizSteps = $('#quizzie .quiz-step'),
    totalScore = 0;

// for each step in the quiz, add the selected answer value to the total score
// if an answer has already been selected, subtract the previous value and update total score with the new selected answer value
// toggle a visual active state to show which option has been selected
quizSteps.each(function () {
    var currentStep = $(this),
        ansOpts = currentStep.children('.quiz-answer');
    // for each option per step, add a click listener
    // apply active class and calculate the total score
    ansOpts.each(function () {
        var eachOpt = $(this);
        eachOpt[0].addEventListener('click', check, false);
        function check() {
            var $this = $(this),
                value = $this.attr('data-quizIndex'),
                answerScore = parseInt(value);
            // check to see if an answer was previously selected
            if (currentStep.children('.active').length > 0) {
                var wasActive = currentStep.children('.active'),
                    oldScoreValue = wasActive.attr('data-quizIndex'),
                    oldScore = parseInt(oldScoreValue);
                // handle visual active state
                currentStep.children('.active').removeClass('active');
                $this.addClass('active');
                // handle the score calculation
                totalScore -= oldScoreValue;
                totalScore += answerScore;
                calcResults(totalScore);
            } else {
                // handle visual active state
                $this.addClass('active');
                // handle score calculation
                totalScore += answerScore;
                calcResults(totalScore);
                // handle current step
                updateStep(currentStep);
            }
        }
    });
});

// show current step/hide other steps
function updateStep(currentStep) {
    if(currentStep.hasClass('current')){
       currentStep.removeClass('current');
       currentStep.next().addClass('current');
    }
}

// display scoring results
function calcResults(totalScore) {
    // only update the results div if all questions have been answered
    if (quizSteps.find('.active').length == quizSteps.length){
        var resultsTitle = $('#results h1'),
            resultsDesc = $('#results .desc');
        
        // calc lowest possible score
        var lowestScoreArray = $('#quizzie .low-value').map(function() {
            return $(this).attr('data-quizIndex');
        });
        var minScore = 0;
        for (var i = 0; i < lowestScoreArray.length; i++) {
            minScore += lowestScoreArray[i] << 0;
        }
        // calculate highest possible score
        var highestScoreArray = $('#quizzie .high-value').map(function() {
            return $(this).attr('data-quizIndex');
        });
        var maxScore = 0;
        for (var i = 0; i < highestScoreArray.length; i++) {
            maxScore += highestScoreArray[i] << 0;
        }
        // calc range, number of possible results, and intervals between results
        var range = maxScore - minScore,
            numResults = resultOptions.length,
            interval = range / (numResults - 1),
            increment = '',
            n = 0; //increment index
        // incrementally increase the possible score, starting at the minScore, until totalScore falls into range. then match that increment index (number of times it took to get totalScore into range) and return the corresponding index results from resultOptions object
        while (n < numResults) {
            increment = minScore + (interval * n);
            if (totalScore <= increment) {
                // populate results
                resultsTitle.replaceWith("<h1>" + resultOptions[n].title + "</h1>");
                resultsDesc.replaceWith("<p class='desc'>" + resultOptions[n].desc + "</p>");
                return;
            } else {
                n++;
            }
        }
    }
}

Embed the quiz component (<div id="quizzie">) wherever you want the quiz to appear on your webpage. Ensure the background and text colors match your website’s theme by adjusting the CSS.

That’s all! hopefully, you have successfully created a simple quiz App on your website. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X