Create Easy Quiz contest using jQuery.

Written By rameshkrr
jQuery

I start with a quote that javascript is an art. This article makes quiz using jQuery very simple. You can make your own questions and answers. In addition download link is at the end of this article.

 

 

You’ve to make some stuff to something happen in javascript. I just used jquery to reduce some lines of codes.
We are going to add three javascript file namely,
  1. jquery(jquery library file)
  2. jquizzy
  3. init.js
First of all, I’m going to show you how to make n number of questions and answer.

Add init file:

var init = { 
     'questions': [ 
       {
           'question': 'jquery is a...',
           'answers': ['JavaScript library','Ruby Gem','PHP Framework','None of the above'],
			  'correctAnswer': 1
       },
       {
           'question': 'jquery used in .. ',
           'answers': ['Frontend','Backend'],
			  'correctAnswer': 1
       },
		 {
           'question': 'Javascript different from Java',
           'answers': ['No, they two are same.','Yes, they are different programming languages'],
			  'correctAnswer': 2
       },
     ],
	  'resultComments' :  
	  {
		    perfect: 'Albus, is that you?',
			 excellent: 'Outstanding, noble sir!',
			 good: 'Exceeds expectations!',
			 average: 'Acceptable. For a muggle.',
			 bad: 'Well, that was poor.',
			 poor: 'Dreadful!',
			 worst: 'For shame, troll!'
	  }

 };

Explanation of jQuery init:

We created variable init as an object. The questions and answers are binds into it. You can add more questions and assign correct answers to it but separate name-value pairs.

Add jquizz code :

(function($) {
    $.fn.jquizzy = function(settings) {
        var defaults = {
            questions: null,
            twitterStatus: 'I scored {score} on this awesome + quiz! http://www.xploiting.com',
            startText: 'Let\'s get started!',
            endText: 'Finished!',
            splashImage: 'img/start1.jpg',
            twitterImage: 'img/share.png',
            resultComments: {
                perfect: 'Perfect!',
                excellent: 'Excellent!',
                good: 'Good!',
                average: 'Acceptable!',
                bad: 'Disappointing!',
                poor: 'Poor!',
                worst: 'Nada!'
            }
        };
        var config = $.extend(defaults, settings);
        if (config.questions === null) {
            $(this).html('

<div class="intro-container slide-container">

<h2 class="qTitle">Failed to parse questions.</h2>

</div>


');
            return
        }
        var superContainer = $(this),
            answers = [],
            introFob = '    

<div class="intro-container slide-container">

<div class="question-number">' + config.startText + '</div>


<a class="nav-start" href="#"><img src="' + config.splashImage + '" /></a></div>


    ',
            exitFob = '

<div class="results-container slide-container">

<div class="question-number">' + config.endText + '</div>


<div class="result-keeper"></div>

</div>


<div class="progress-keeper" >

<div class="progress"></div>

</div>


<div class="notice">Please select an option</div>


',
            contentFob = '';
        superContainer.addClass('main-quiz-holder');
        for (questionsIteratorIndex = 0; questionsIteratorIndex < config.questions.length; questionsIteratorIndex++) {
            contentFob += '

<div class="slide-container">

<div class="question-number">' + (questionsIteratorIndex + 1) + '/' + config.questions.length + '</div>


<div class="question">' + config.questions[questionsIteratorIndex].question + '</div>


<ul class="answers">';
            for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[questionsIteratorIndex].answers.length; answersIteratorIndex++) {
                contentFob += '

<li>' + config.questions[questionsIteratorIndex].answers[answersIteratorIndex] + '</li>


'
            }
            contentFob += '</ul>


<div class="nav-container">
';
            if (questionsIteratorIndex !== 0) {
                contentFob += '

<div class="prev"><a class="nav-previous" href="#">Prev</a></div>


'
            }
            if (questionsIteratorIndex < config.questions.length - 1) {
                contentFob += '

<div class="next"><a class="nav-next" href="#">Next</a></div>


'
            } else {
                contentFob += '

<div class="next final"><a class="nav-show-result" href="#">Finish</a></div>


'
            }
            contentFob += '</div>

</div>


';
            answers.push(config.questions[questionsIteratorIndex].correctAnswer)
        }
        superContainer.html(introFob + contentFob + exitFob);
        var progress = superContainer.find('.progress'),
            progressKeeper = superContainer.find('.progress-keeper'),
            notice = superContainer.find('.notice'),
            progressWidth = progressKeeper.width(),
            userAnswers = [],
            questionLength = config.questions.length,
            slidesList = superContainer.find('.slide-container');

        function checkAnswers() {
            var resultArr = [],
                flag = false;
            for (i = 0; i < answers.length; i++) { if (answers[i] == userAnswers[i]) { flag = true } else { flag = false } resultArr.push(flag) } return resultArr } function roundReloaded(num, dec) { var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); return result } function judgeSkills(score) { var returnString; if (score == 100) return config.resultComments.perfect; else if (score > 90) return config.resultComments.excellent;
            else if (score > 70) return config.resultComments.good;
            else if (score > 50) return config.resultComments.average;
            else if (score > 35) return config.resultComments.bad;
            else if (score > 20) return config.resultComments.poor;
            else return config.resultComments.worst
        }
        progressKeeper.hide();
        notice.hide();
        slidesList.hide().first().fadeIn(500);
        superContainer.find('li').click(function() {
            var thisLi = $(this);
            if (thisLi.hasClass('selected')) {
                thisLi.removeClass('selected')
            } else {
                thisLi.parents('.answers').children('li').removeClass('selected');
                thisLi.addClass('selected')
            }
        });
        superContainer.find('.nav-start').click(function() {
            $(this).parents('.slide-container').fadeOut(500, function() {
                $(this).next().fadeIn(500);
                progressKeeper.fadeIn(500)
            });
            return false
        });
        superContainer.find('.next').click(function() {
            if ($(this).parents('.slide-container').find('li.selected').length === 0) {
                notice.fadeIn(300);
                return false
            }
            notice.hide();
            $(this).parents('.slide-container').fadeOut(500, function() {
                $(this).next().fadeIn(500)
            });
            progress.animate({
                width: progress.width() + Math.round(progressWidth / questionLength)
            }, 500);
            return false
        });
        superContainer.find('.prev').click(function() {
            notice.hide();
            $(this).parents('.slide-container').fadeOut(500, function() {
                $(this).prev().fadeIn(500)
            });
            progress.animate({
                width: progress.width() - Math.round(progressWidth / questionLength)
            }, 500);
            return false
        });
        superContainer.find('.final').click(function() {
            if ($(this).parents('.slide-container').find('li.selected').length === 0) {
                notice.fadeIn(300);
                return false
            }
            superContainer.find('li.selected').each(function(index) {
                userAnswers.push($(this).parents('.answers').children('li').index($(this).parents('.answers').find('li.selected')) + 1)
            });
            progressKeeper.hide();
            var results = checkAnswers(),
                resultSet = '',
                trueCount = 0,
                shareButton = '',
                score;
            for (var i = 0, toLoopTill = results.length; i < toLoopTill; i++) {
                if (results[i] === true) {
                    trueCount++;
                    isCorrect = true
                }
                resultSet += '

<div class="result-row">
 Question #' + (i + 1) + (results[i] === true ? "

<div class='correct'><span>Correct</span></div>


" : "

<div class='wrong'><span>Incorrect</span></div>


");
                resultSet += '

<div class="resultsview-qhover">
' + config.questions[i].question;
                resultSet += "

<ul>";
                for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[i].answers.length; answersIteratorIndex++) {
                    var classestoAdd = '';
                    if (config.questions[i].correctAnswer == answersIteratorIndex + 1) {
                        classestoAdd += 'right'
                    }
                    if (userAnswers[i] == answersIteratorIndex + 1) {
                        classestoAdd += ' selected'
                    }
                    resultSet += '

<li class="' + classestoAdd + '">' + config.questions[i].answers[answersIteratorIndex] + '</li>


'
                }
                resultSet += "</ul>

</div>

</div>


"
            }
            score = roundReloaded(trueCount / questionLength * 100, 2);
            shareButton = '<a href=" " class="share-button"><img src="' + config.twitterImage + '" /></a>';
            resultSet = '

<h2 class="qTitle">' + judgeSkills(score) + ' You scored ' + score + '%</h2>


' + shareButton + resultSet;
            superContainer.find('.result-keeper').html(resultSet).show(500);
            superContainer.find('.resultsview-qhover').hide();
            superContainer.find('.result-row').hover(function() {
                $(this).find('.resultsview-qhover').show()
            }, function() {
                $(this).find('.resultsview-qhover').hide()
            });
            $(this).parents('.slide-container').fadeOut(500, function() {
                $(this).next().fadeIn(500)
            });
            return false
        })
    }
})(jQuery);

Explanation of  jQuery:

(function($){
//Code here
})(jQuery);

This is known as self-invoked function. Basically, this is an anonymous function without a name.  The self-invoked or self-calling function doesn’t require to call it.It starts to execute when DOM loaded.

In jquery, the propertyfn is just an alias to the propertyprototype. The identifierjQuery (or $) is just a constructor function, and all instances created with it, inherit from the constructor’s prototype.

The variable defaultsforms another set of object to store some of the important values like intro text, image source and so on.

The propertyextend in jquery merges the contents of two or more objects together into the first object. Here we merge defaults and settingswhere the variableconfig stores all objects name-value pairs.

The appending of HTML attributes using jquery is handled so long in this scripts. The closure concept is used here. checkAnswers()is a function used to cross-check the input from the user with correct answers.

Add index:



<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Bootstrap 101 Template</title>
      <link rel='stylesheet' href='css/styles.css' />
      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D'js%2Fjquery.js'%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D'js%2Fjquery.jquizzy-min.js'%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D'init.js'%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
      
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%20type%3D%22text%2Fcss%22%3E%0A%20%20%20%20%20%20%20%20%20.nav-start%20img%20%7B%0A%20%20%20%20%20%20%20%20%20width%3A%20509px%3B%0A%20%20%20%20%20%20%20%20%20margin-top%3A%2043px%3B%0A%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />

   </head>
   <body>
      
<h1 style="text-align: center">Quiz By Xploiting!</h1>

      
<div id='quiz-container'></div>

      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20%20%20%20%20%20%20%20%24('%23quiz-container').jquizzy(%7B%0A%20%20%20%20%20%20%20%20%20%09%09questions%3A%20init.questions%2C%20%0A%20%20%20%20%20%20%20%20%20%09%09resultComments%3A%20init.resultComments%2C%0A%20%20%20%20%20%20%20%20%20%09%09twitterStatus%3A%20'Woo!%20I%20got%20%7Bscore%7D%20on%20the%20quiz.%20Try%20it!%20http%3A%2F%2Fwww.xploiting.com'%2C%0A%20%20%20%20%20%20%20%20%20%09%7D)%3B%0A%20%20%20%20%20%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
   </body>
</html>


	 

Index Explanation:

We are adding three javascript files and one CSS files into our index file. First one is jquery library file. The second is a quiz code. The third one in a init file to add, remove questions and answer.

Above are some basic stuff probably you should recognize it. Download source code and try yourself.

 

 

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*