Advertisement
  1. Code
  2. JavaScript

Build a Spiffy Quiz Engine

Scroll to top

The first official Nettuts+ quiz was a massive success with an impressive number of developers participating and evaluating their knowledge. There were a non-trivial number of comments asking how the mini quiz engine was built. And lo and behold! That's what we're gonna learn today.


A Word from the Author

Quizzes are a great way to engage the community -- just take a look at our recent quiz. The problem is that, in this day and age, people expect quizzes to be fairly interactive and my Google-fu failed strongly when searching for a system that eases the process. That's when I decided to build myself, and Nettuts, a super simple quiz engine, one that I playfully call kroggy.

I believe a demo is worth a thousand words. Hit the demo and try it out for yourselves.

Today, we are going to look at how to implement this with, you guessed it right, our favorite JavaScript library, jQuery. Interested? Let's get started right away!


Design Goals

The design goal for this version are incredibly simple. I'll walk you through the points I had in mind.

  • We'll something that looks slick and elegant -- one that invites the user to take the quiz.
  • This is no place for a long list of questions with radio buttons and labels. We'll need to implement a simple slider of some sort to view each question individually.
  • Questions will be evaluated at the end of the quiz instead of immediately. This way the reader can focus on the quiz taking process instead of having to pause each time to evaluate the result.
  • A simple progress bar at the bottom to display the user's progress.
  • The correct answers can live in either the JavaScript or the HTML. This isn't the SATs -- no need to introduce more complexity to our fledgling codebase.

Some notable features that I'm opting out of:

  • No post quiz reviews. Doing so would have us scraping our own HTML for data and then re-rendering it. Not fun! And definitely not within the scope of today's tutorial.
  • We are not going to wrap this up into a plugin. We're better off focusing on the actual development portion of the functionality. There are plenty of content on how to refactor code into a jQuery plugin.
  • As an extension of the above point, it also means that the HTML for the quizzes will be pre-written by us -- it won't be generated and inserted dynamically.

That's about it, I guess. Let's move on to how we're going to accomplish this.


Plan of Action

We'll now need to map out what needs to be done in a specific order.

  • Step 1: Create the HTML markup for the base quiz engine and style it accordingly.
  • Step 2: When a user has selected an option and clicks the next button, just silently move to the next question. If no option is selected, throw an error.
  • Step 3: When the user is on the final question and clicks on the next button, raise hell and evaluate results like so.
  • Step 4: Find out which option the user has selected and match it to the list of predefined answers. Return a simple array so we can evaluate the results later and present some data in the final screen.

Ok, that sounds reasonably easy.These are the basic steps in creating this functionality. Of course there are few other small things but I’ll explain them as we go along.

Now let's dig into some code and get our hands dirty. First, the HTML.


Core Markup

The markup is one of the pillars that holds this engine up so we'll go through each part individually with the entire code shown at the end to show the big picture.

1
<div id="main-quiz-holder"> 
2
</div>

A div element with an ID of main-quiz-holder will be the main container within which we're going to place our entire HTML code -- all the code below goes inside this div element.

1
 
2
<div class="questionContainer"> 
3
</div>

Next up, let's create a sample slide of the quiz. Remember that we're going to create a super simple slider to hold our individual questions. Each slide will be housed with a div element with a class of questionContainer.

Before we go into the markup of a quiz slide, let's handle a few formalities.

1
 
2
<div id="intro-container" class="questionContainer"> 
3
	<a class="btnStart" href="#"><img src="img/start.png" /></a>    
4
</div>

The above code is for the intro container, the one which is displayed asking the user to take the quiz. We're just adding an ID of intro-container to it to help us style it better later.

Inside the div, we merely have a single splash image wrapped by an anchor element.

1
 
2
<div id="results-container" class="questionContainer"> 
3
    <div id="resultKeeper"></div> 
4
</div>

And the results slide. Nothing special here: we assign a special ID and place an empty div inside it to hold our results. We'll populate this element down the road when we're evaluating the results.

If you noticed the class of questionContainer for both this and the slide above, gold star for you! We're adding this class since both these containers are part of the slider.

1
 
2
<div id="progressKeeper" ><div id="progress"></div></div> 
3
<div id="notice">Please select an option</div>

And finally, a little housekeeping. We create div elements for the progress bar container, the actual bar itself and the notice that'll be shown in case the user doesn't select an option.

With this, our skeleton markup is over.


Markup for Each Question

Ahh, the meaty part of the markup is upon us. These sections may look complicated but as always, I'll break it down into smaller chunks and walk you through the code.

1
 
2
<div class="questionContainer"> 
3
	<div class="question">Question</div> 
4
 		<!-- UL with options --> 
5
        <div class="btnContainer"> 
6
				<!-- Internal navigation links --> 
7
        </div> 
8
	</div> 
9
</div>

As mentioned previously, we'll be wrapping each of our quiz slides with a div element with a class of questionContainer. Inside, we have a div element with a class of question that contains each of our questions.

We follow it up with an unordered list containing the possible answers to the question and a div acting as the container for the navigation elements [previous/next]. Make a note of the class name of each of these sections.

1
 
2
<ul class="answers"> 
3
    <li> 
4
        <label><input data-key="a" type="radio">lend structure to the document</label> 
5
    </li> 
6
    <li> 
7
        <label><input data-key="b" type="radio">mold the presentation of the document</label> 
8
    </li> 
9
    <li> 
10
        <label><input data-key="c" type="radio">script the interactions on the page</label> 
11
    </li> 
12
    <li> 
13
        <label><input data-key="d" type="radio">You're crafty! This is a trick question.</label> 
14
    </li> 
15
</ul>

Expanding on our unordered list, each li element has a label element containing a single radio button. Notice that we're assigning each radio a data-key attribute? We'll look at it a bit later.

1
 
2
<div class="btnContainer"> 
3
	<div class="prev"><a class="btnPrev" href="#">Prev</a></div> 
4
	<div class="next"><a class="btnNext"  href="#">Next</a></div> 
5
	<div class="clear"></div> 
6
</div>

And finally, the navigation container. Nothing fancy here. We have a main div with a class of btnContainer that acts as the container. Inside we have an anchor wrapped by a div element. The div is merely for styling purposes so feel free to discard that in your implementation.

Keep in mind that the previous and next buttons have to be inserted logically. You wouldn't want a previous button on the first actual quiz slide while the final slide needs to have the button to trigger the evaluation process.

Instead of the next button the final slide needs to have the following:

1
 
2
<div class="next"><a class="btnShowResult" href="#">Finish</a></div>

And that wraps up the HTML portion of our quiz slides. You'll notice that we haven't tackled the HTML for the quiz results. We'll tackle that during the JavaScript phase. For now, let's move on to the presentation.


Final HTML

1
 
2
<div id="main-quiz-holder"> 
3
	<div id="intro-container" class="questionContainer"> 
4
		<a class="btnStart" href="#"><img src="img/start.png"/></a> 
5
	</div> 
6
	<div class="questionContainer hide"> 
7
		<div class="question"> 
8
			CSS is used to... 
9
		</div> 
10
		<ul class="answers"> 
11
			<li> 
12
			<label><input data-key="a" type="radio">lend structure to the document</label> 
13
			</li> 
14
			<li> 
15
			<label><input data-key="b" type="radio">mold the presentation of the document</label> 
16
			</li> 
17
			<li> 
18
			<label><input data-key="c" type="radio">script the interactions on the page</label> 
19
			</li> 
20
			<li> 
21
			<label><input data-key="d" type="radio">You're crafty! This is a trick question.</label> 
22
			</li> 
23
		</ul> 
24
		<div class="btnContainer"> 
25
			<div class="next"> 
26
				<a class="btnNext" href="#">Next</a> 
27
			</div> 
28
			<div class="clear"> 
29
			</div> 
30
		</div> 
31
	</div> 
32
	<div class="questionContainer hide"> 
33
		<div class="question"> 
34
			The C in CSS stands for? 
35
		</div> 
36
		<ul class="answers"> 
37
			<li> 
38
			<label><input data-key="a" type="radio">Crysis</label> 
39
			</li> 
40
			<li> 
41
			<label><input data-key="b" type="radio">Crocodile</label> 
42
			</li> 
43
			<li> 
44
			<label><input data-key="c" type="radio">Consistent</label> 
45
			</li> 
46
			<li> 
47
			<label><input data-key="d" type="radio">Cascading</label> 
48
			</li> 
49
		</ul> 
50
		<div class="btnContainer"> 
51
			<div class="prev"> 
52
				<a class="btnPrev" href="#">Prev</a> 
53
			</div> 
54
			<div class="next"> 
55
				<a class="btnNext" href="#">Next</a> 
56
			</div> 
57
			<div class="clear"> 
58
			</div> 
59
		</div> 
60
	</div> 
61
	<!-- More questions here --> 
62
	<div class="questionContainer hide"> 
63
		<div class="question"> 
64
			The * selector selects... 
65
		</div> 
66
		<ul class="answers"> 
67
			<li> 
68
			<label><input data-key="a" type="radio">every div element</label> 
69
			</li> 
70
			<li> 
71
			<label><input data-key="b" type="radio">only paragraphs</label> 
72
			</li> 
73
			<li> 
74
			<label><input data-key="c" type="radio">only parent elements</label> 
75
			</li> 
76
			<li> 
77
			<label><input data-key="d" type="radio">every element</label> 
78
			</li> 
79
		</ul> 
80
		<div class="btnContainer"> 
81
			<div class="prev"> 
82
				<a class="btnPrev" href="#">Prev</a> 
83
			</div> 
84
			<div class="next"> 
85
				<a class="btnShowResult" href="#">Finish</a> 
86
			</div> 
87
			<div class="clear"> 
88
			</div> 
89
		</div> 
90
	</div> 
91
	<div id="results-container" class="questionContainer hide"> 
92
		<div id="resultKeeper"> 
93
		</div> 
94
	</div> 
95
	<div id="progressKeeper"> 
96
		<div id="progress"> 
97
		</div> 
98
	</div> 
99
	<div id="notice"> 
100
		Please select an option 
101
	</div> 
102
</div>

At the end of this phase, our page looks like so:



Core CSS

Let's start making our quiz look sleek and attractive. First, the main container.

1
 
2
#main-quiz-holder { 
3
	margin: 0 auto; 
4
	position: relative; 
5
	background: #FCFCFC; 
6
    border:1px solid #dedede; 
7
	 box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
8
	 -o-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
9
	 -webkit-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
10
	 -moz-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
11
	 border-radius: 2px; 
12
	 position: relative; 
13
	 width: 600px; 
14
	 font-family:  "Myriad", "Myriad Pro", "Helvetica","Segoe UI", "Lucida Sans Unicode", "Lucida Grande", sans-serif; 
15
}

Basically we're centering it, giving it a background and a border to make it stand out. The CSS3 properties may look a little confusing but it's mainly because of the browser specific properties. We're simply defining a box shadow for the container here -- nothing complicated once you learn the syntax.

1
 
2
#results-container, #intro-container { 
3
	width: 500px; 
4
	text-align: center; 
5
}

Let's define a width and center the contents of the intro and final slide. This way we don't have to style each individually since both of their contents will have to be centered anyway.

1
 
2
.questionContainer .question, h2.qTitle { 
3
    margin: 10px 0 20px 0; 
4
	 font-size: 26px; 
5
	 font-weight: normal; 
6
} 
7
h2.qTitle { 
8
	font-size: 32px; 
9
	margin-top: 30px; 
10
}

Let's style our titles and questions now. Since we want them to stand out amidst the other elements, we're bumping up the font sizes and giving them sizeable margins on either side. Rememeber, oodles of white space helps frame the content better.

1
 
2
#progressKeeper { 
3
    width: 553px; 
4
    margin: 0px 12px; 
5
	 box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
6
	 -o-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
7
	 -webkit-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
8
	 -moz-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
9
	 border-radius: 2px; 
10
	 border:1px solid #dedede; 
11
	 position: absolute; 
12
	 bottom: 10px; 
13
	 left: 10px; 
14
}

On to the progress bar container now. The first thing you'll need to make a note of is the position: absolute declaration. We're adding this since we need this element to remain fixed within the parent container

The bottom and left properties specify that it should be fixed at the bottom of the container. The rest of the CSS is merely for styling purposes.

1
 
2
 #progress { 
3
    width: 0; 
4
	 height: 20px; 
5
  color: #4c4c4c; 
6
  background: #f6f6f6; 
7
  background: -webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#d4d4d4)); 
8
  background: -webkit-linear-gradient(#f6f6f6, #d4d4d4); 
9
  background-image: -moz-linear-gradient(top, #f6f6f6, #d4d4d4); 
10
  background-image: -moz-gradient(top, #f6f6f6, #d4d4d4); 
11
 }

And now the actual progress bar. We want it to be understated and yet prominent enough so I'm going with a slight grey gradient. As mentioned previously, this may look complicated but it's because of the relatively complex syntax of the CSS3 gradient property.

1
 
2
#notice { 
3
	position: absolute; 
4
	bottom: 40px; 
5
	right: 20px; 
6
}

notice is the div element that holds the error notice when the user screws up, say, when he hasn't chosen an option. To make things simpler, I've chosen to position it absolutely, just above the progress bar.


Question Slide CSS

1
 
2
.questionContainer { 
3
    width: 560px; 
4
	 min-height: 400px; 
5
    padding: 20px; 
6
	 overflow: auto; 
7
	 margin: auto; 
8
}

On to the slide container, questionContainer, first. We're defining a fixed width so that we can center it properly. We're also defining a minimum width so it doesn't break with fewer options. Finally, we're adding a bit of padding to improve the presentation and adding a overflow: auto declaration to deal with floated child elements.

1
 
2
.questionContainer ul.answers { 
3
    margin: 0px; 
4
    padding: 5px; 
5
	 list-style: none; 
6
}

Let's deal with the answers list next. We're merely removing the styling for the list by applying list-style: none and a little margin and spacing for better presentation.

1
 
2
.questionContainer ul.answers li { 
3
	padding: 5px 50px; 
4
	margin: 12px 0; 
5
	color: #4c4c4c; 
6
  -webkit-border-radius: 4px; 
7
  -moz-border-radius: 4px; 
8
  border-radius: 4px; 
9
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
10
  -webkit-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
11
  -moz-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
12
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
13
  background: #f6f6f6; 
14
  background: -webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#d4d4d4)); 
15
  background: -webkit-linear-gradient(#f6f6f6, #d4d4d4); 
16
  background-image: -moz-linear-gradient(top, #f6f6f6, #d4d4d4); 
17
  background-image: -moz-gradient(top, #f6f6f6, #d4d4d4); 
18
  border: 1px solid #a1a1a1;	 
19
}

The above is the styling for the individual list elements. The CSS can be split into 3 sections.

  • The first few lines are very basic -- we add a little margin and padding, specify a color for the text inside and add a little border radius.
  • Next up, we're using the CSS3 box shadow property to make it look better. Note the different prefixes for different browsers.
  • Finally, we're handling the background of the element. We're specifying a greyi-ish gradient to be displayed.
1
 
2
.questionContainer ul.answers li.selected { 
3
	background: #6fb2e5; 
4
  box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
5
   -o-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
6
   -webkit-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
7
   -moz-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
8
}

On to the styling for the li element when it has been selected by the user. We need it to really stand out to help the user experience. With that in mind, I'm opting for a bright blue background to be applied.


CSS for the Navigation Elements

1
 
2
.questionContainer .prev, .questionContainer .next { 
3
	height: 19px;  
4
	cursor: pointer;  
5
	padding: 5px 10px; 
6
   font-size: 16px; 
7
   padding: 5px 10px; 
8
  color: #4c4c4c; 
9
  border-radius: 4px; 
10
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
11
  background: #6fb2e5; 
12
  box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
13
   -o-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
14
   -webkit-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
15
   -moz-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
16
}

Let's go ahead and style the div elements holding the navigation elements. Most of the code above should be fairly explanatory. We're defining some padding to frame the text inside better, assigning it a color, increasing the font size a bit and adding some rounder corners. And finally, we're adding some CSS3 box shadows to make it look spiffy.

1
 
2
.questionContainer .next  { 
3
  background: #77d125; 
4
  box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
5
   -o-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
6
   -webkit-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
7
   -moz-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
8
}

Since we want the next button to look different, we're overriding some of the styles from above. Here, I'm moving the main shade from blue to green.

1
 
2
.questionContainer .prev { float: left;} 
3
.questionContainer .next, .questionContainer.btnShowResult { float: right; } 
4
.questionContainer .clear { clear: both; }

This'll take care of the position for each of the buttons. We want the previous button floated to the left while the next and final buttons need to be floated to the right. That's precisely what the above code does.

1
 
2
.btnPrev { 
3
	padding-left: 24px; 
4
	background: url(img/back.png) left no-repeat; 
5
} 
6
.btnNext { 
7
	padding-right: 24px; 
8
	background: url(img/forward.png) right no-repeat; 
9
} 
10
.btnShowResult{ 
11
	padding-left: 24px; 
12
	background: url(img/confirm.png) left no-repeat; 
13
} 
14
.btnStart { 
15
	display: block; 
16
	margin: 40px auto 0 auto; 
17
} 
18
.btnContainer { 
19
	margin: 20px 0 30px 0; 
20
	padding: 5px; 
21
}

During the HTML phase you must have noticed that the buttons themselves have a parent div element with a child link element. We styled the parent elements in the previous code block. The above handles the child links.

Basically, the above code inserts the little graphic into the buttons. We're adding a little padding so the text is nicely offset. Notice how we change between padding-left and padding-right to style each element precisely.

The btnContainer itself gets a little margin and padding to position it where we want.


Styling the Results

Phew! Most of the CSS work is now behind us. Let's tackle the final piece of CSS -- the final slide which displays the results. Since you haven't seen the HTML, yet, it may be a little confusing but the CSS show be fairly generic and easy to parse.

1
 
2
.resultRow { 
3
	width: 110px; 
4
	margin: 10px 25px; 
5
	float: left; 
6
}

Let's start off small. We're going to be assigning each 'cell' of the results the class of resultRow. Since we want it presented neatly, we're going to be floating everything to the left so it forms a neat three column stack of results. This section is supposed to look like so after we've finished:


1
 
2
.correct, .wrong {     
3
	height: 19px; 
4
	cursor: pointer;  
5
   font-size: 16px; 
6
   padding: 5px 15px; 
7
  color: #4c4c4c; 
8
  border-radius: 4px; 
9
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
10
  -webkit-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
11
  -moz-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
12
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
13
}

Let's define the base of these blocks. As always, I'm using a little CSS3 to make the sections stand out. Other than that, the CSS is pretty simple -- a little padding, rounded corners and such.

1
 
2
.correct {     
3
  background: #b2d840; 
4
  background: -webkit-gradient(linear, left top, left bottom, from(#b2d840), to(#90b61e)); 
5
  background: -webkit-linear-gradient(#b2d840, #90b61e); 
6
  background-image: -moz-linear-gradient(top, #b2d840, #90b61e); 
7
  background-image: -moz-gradient(top, #b2d840, #90b61e); 
8
  border: 1px solid #5d8300; 
9
} 
10
.wrong { 
11
	background: #e84545; 
12
  background: -webkit-gradient(linear, left top, left bottom, from(#e84545), to(#c62323)); 
13
  background: -webkit-linear-gradient(#e84545, #c62323); 
14
  background-image: -moz-linear-gradient(top, #e84545, #c62323); 
15
  background-image: -moz-gradient(top, #e84545, #c62323); 
16
  border: 1px solid #930000; 
17
  color: #F1F1F1; 
18
}

We'll need to make the right and wrong answers stand out visually so here goes. Using CSS3 we're applying a green tinged gradient to all the right answers while the wrong 'uns get the red treatment. Nothing special going on here. Master the syntax and you should be all set.

1
 
2
.correct span { 
3
	padding: 0 20px; 
4
	background: url(img/confirm.png) left no-repeat; 
5
} 
6
.wrong span { 
7
	padding: 0 20px; 
8
	background: url(img/delete.png) left no-repeat; 
9
}

Let's add a little imagery to make the entire thing look more cohesive. We're adding some simple icons inside the buttons as shown above.

1
 
2
#answer-key { 
3
	text-align: center; 
4
	width: 300px; 
5
	padding: 15px; 
6
	margin: 0 auto; 
7
	 clear: both; 
8
	 font-size: 16px; 
9
}

And finally, let's style the answer key container. A little padding and margins help us make it look better. We're also making sure it is centered and setting the font size to an appropriate value.


The Final CSS

I skipped a few generic portions of the CSS along the way so here's the complete CSS at this point:

1
 
2
#main-quiz-holder { 
3
	margin: 0 auto; 
4
	position: relative;background: #FCFCFC; 
5
    border:1px solid #dedede; 
6
	 box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
7
	 -o-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
8
	 -webkit-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
9
	 -moz-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
10
	 border-radius: 2px; 
11
	 position: relative; 
12
	 width: 600px; 
13
	 font-family:  "Myriad", "Myriad Pro", "Helvetica","Segoe UI", "Lucida Sans Unicode", "Lucida Grande", sans-serif; 
14
} 
15
#main-quiz-holder a { 
16
	text-decoration: none; 
17
} 
18
#results-container, #intro-container { 
19
	width: 500px; 
20
	text-align: center; 
21
} 
22
.questionContainer { 
23
    width: 560px; 
24
	 min-height: 400px; 
25
    padding: 20px; 
26
	 overflow: auto; 
27
	 margin: auto; 
28
} 
29
.questionContainer .question, h2.qTitle { 
30
    margin: 10px 0 20px 0; 
31
	 font-size: 26px; 
32
	 font-weight: normal; 
33
} 
34
h2.qTitle { 
35
	font-size: 32px; 
36
	margin-top: 30px; 
37
} 
38
.questionContainer ul.answers { 
39
    margin: 0px; 
40
    padding: 5px; 
41
	 list-style: none; 
42
} 
43
.questionContainer ul.answers li { 
44
	padding: 5px 50px; 
45
	margin: 12px 0; 
46
	color: #4c4c4c; 
47
  -webkit-border-radius: 4px; 
48
  -moz-border-radius: 4px; 
49
  border-radius: 4px; 
50
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
51
  -webkit-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
52
  -moz-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
53
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
54
  background: #f6f6f6; 
55
  background: -webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#d4d4d4)); 
56
  background: -webkit-linear-gradient(#f6f6f6, #d4d4d4); 
57
  background-image: -moz-linear-gradient(top, #f6f6f6, #d4d4d4); 
58
  background-image: -moz-gradient(top, #f6f6f6, #d4d4d4); 
59
  border: 1px solid #a1a1a1;	 
60
} 
61
.questionContainer ul.answers li.selected { 
62
	background: #6fb2e5; 
63
  box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
64
   -o-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
65
   -webkit-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
66
   -moz-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
67
} 
68
.questionContainer .prev, .questionContainer .next { 
69
	height: 19px; cursor: pointer; padding: 5px 10px; 
70
   font-size: 16px; 
71
   padding: 5px 10px; 
72
  color: #4c4c4c; 
73
  border-radius: 4px; 
74
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
75
  background: #6fb2e5; 
76
  box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
77
   -o-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
78
   -webkit-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
79
   -moz-box-shadow: 0 1px 5px #0061aa, inset 0 10px 20px #b6f9ff; 
80
} 
81
.questionContainer .next  { 
82
  background: #77d125; 
83
  box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
84
   -o-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
85
   -webkit-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
86
   -moz-box-shadow: 0 1px 5px #3caa00, inset 0 10px 20px #c9ffb6; 
87
} 
88
#progressKeeper { 
89
    width: 553px; 
90
    margin: 0px 12px; 
91
	 box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
92
	 -o-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
93
	 -webkit-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
94
	 -moz-box-shadow:0 1px 5px #D9D9D9,inset 0 10px 20px #F1F1F1; 
95
	 border-radius: 2px; 
96
	 border:1px solid #dedede; 
97
	 position: absolute; 
98
	 bottom: 10px; 
99
	 left: 10px; 
100
} 
101
 #progress { 
102
    width: 0; 
103
	 height: 20px; 
104
  color: #4c4c4c; 
105
  background: #f6f6f6; 
106
  background: -webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#d4d4d4)); 
107
  background: -webkit-linear-gradient(#f6f6f6, #d4d4d4); 
108
  background-image: -moz-linear-gradient(top, #f6f6f6, #d4d4d4); 
109
  background-image: -moz-gradient(top, #f6f6f6, #d4d4d4); 
110
 } 
111
#resultKeeper { 
112
    margin: 10px; 
113
	 text-align: center; 
114
	 overflow: auto; 
115
} 
116
#notice { 
117
	position: absolute; 
118
	bottom: 40px; 
119
	right: 20px; 
120
} 
121
.questionContainer .prev { float: left;} 
122
.questionContainer .next, .questionContainer.btnShowResult { float: right; } 
123
.questionContainer .clear { clear: both; } 
124
.hide { display: none; } 
125
.btnPrev { 
126
	padding-left: 24px; 
127
	background: url(img/back.png) left no-repeat; 
128
} 
129
.btnNext { 
130
	padding-right: 24px; 
131
	background: url(img/forward.png) right no-repeat; 
132
} 
133
.btnShowResult{ 
134
	padding-left: 24px; 
135
	background: url(img/confirm.png) left no-repeat; 
136
} 
137
.btnStart { 
138
	display: block; 
139
	margin: 40px auto 0 auto; 
140
} 
141
.btnContainer { 
142
	margin: 20px 0 30px 0; 
143
	padding: 5px; 
144
} 
145
.resultRow { 
146
	width: 110px; 
147
	margin: 10px 25px; 
148
	float: left; 
149
} 
150
.correct, .wrong {     
151
	height: 19px; cursor: pointer; padding: 5px 10px; 
152
   font-size: 16px; 
153
   padding: 5px 15px; 
154
  color: #4c4c4c; 
155
  border-radius: 4px; 
156
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); 
157
  -webkit-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
158
  -moz-box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
159
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), inset 0 0 6px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.4); 
160
} 
161
.correct {     
162
  background: #b2d840; 
163
  background: -webkit-gradient(linear, left top, left bottom, from(#b2d840), to(#90b61e)); 
164
  background: -webkit-linear-gradient(#b2d840, #90b61e); 
165
  background-image: -moz-linear-gradient(top, #b2d840, #90b61e); 
166
  background-image: -moz-gradient(top, #b2d840, #90b61e); 
167
  border: 1px solid #5d8300; 
168
} 
169
.wrong { 
170
	background: #e84545; 
171
  background: -webkit-gradient(linear, left top, left bottom, from(#e84545), to(#c62323)); 
172
  background: -webkit-linear-gradient(#e84545, #c62323); 
173
  background-image: -moz-linear-gradient(top, #e84545, #c62323); 
174
  background-image: -moz-gradient(top, #e84545, #c62323); 
175
  border: 1px solid #930000; 
176
  color: #F1F1F1; 
177
} 
178
.correct span { 
179
	padding: 0 20px; 
180
	background: url(img/confirm.png) left no-repeat; 
181
} 
182
.wrong span { 
183
	padding: 0 20px; 
184
	background: url(img/delete.png) left no-repeat; 
185
} 
186
#answer-key { 
187
	text-align: center; 
188
	width: 300px; 
189
	padding: 15px; 
190
	margin: 0 auto; 
191
	 clear: both; 
192
	 font-size: 16px; 
193
}

With everything but the JavaScript in place, our engine should look as shown below:



The JavaScript Interaction

The JavaScript, though shorter than you'd expect, is the heart and soul of the mini-engine. As I mentioned earlier, this is some pretty alpha code so make sure to clean things up before deployment.

As always, let's tackle the code one section at a time.


First, the Basics

We're going to handle some of the boilerplate elements first up.

1
 
2
$(function(){ 
3
// Everything that follows goes in here 
4
})

Let's place all our code into the block above -- a self executing anonymous function. This way our variables will be nicely namespaced thus avoiding naming collisions in the future.

1
 
2
var progress = $('#progress'), 
3
	progressKeeper = $('#progressKeeper'), 
4
	notice = $("#notice"), 
5
	progressWidth = 548, 
6
	answers= kroggy.answers, 
7
	userAnswers = [], 
8
	questionLength= answers.length, 
9
	questionsStatus = $("#questionNumber") 
10
	questionsList = $(".question");

And this is the variables we'll be using today. The names should make their purpose completely obvious. We also cache a few important elements for use later. An important point to make note of is how we're assigning answers the value of kroggy.answers. I'll explain it right below.

1
 
2
var kroggy = { answers: [ 'b', 'd', 'a', 'c', 'a', 'd', 'b', 'a', 'd', 'a', 'd', 'c', 'a', 'b', 'd' ] }

If you looked through the demo, you'll notice a small script tag holding the above code. What we're doing here is create an object called kroggy and place the answer key to our quiz inside an array called answers. This is the value we assigned to the variable answers earlier.


Creating the Helper Functions

Before we hop off into creating the actual code, let's deal with a few small helper methods first. In increasing order of importance.

1
 
2
function roundReloaded(num, dec) { 
3
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); 
4
	return result; 
5
}

I couldn't find a decent enough rounding method predefined in JavaScript so I went ahead and put together a little something.

You'll need to send in a value and the number of significant digits to round off too and the function does the rest. Since the logic is incredibly simple, I'll let you parse the rest.

1
 
2
function judgeSkills(score) { 
3
	var returnString; 
4
		if (score==100) returnString = "Albus, is that you?" 
5
		else if (score>90) returnString = "Outstanding, noble sir!" 
6
		else if (score>70) returnString = "Exceeds expectations!" 
7
		else if (score>50) returnString = "Acceptable. For a muggle." 
8
		else if (score>35) returnString = "Well, that was poor." 
9
		else if (score>20) returnString = "Dreadful!" 
10
		else returnString = "For shame, troll!" 
11
	return returnString; 
12
}

The comments on the result screen netted a lot of hilarious comments and amusement among the quiz takers and this is where the magic happens.

Again, pretty basic programming that's going on here. The function takes the score as the parameter and returns a comment.

Here, the conditions are arbitrary but I think they do a fairly good job. Feel free to play around with the conditions in your project.

1
 
2
function checkAnswers() { 
3
	var resultArr = [],  
4
				flag = false; 
5
	for (i=0; i<answers.length; i++) { 
6
	    if (answers[i] == userAnswers[i]) { 
7
	        flag = true; 
8
	    } 
9
	    else { 
10
	        flag = false; 
11
	    } 
12
	    resultArr.push(flag); 
13
	} 
14
	return resultArr; 
15
}

This is the primary function that evaluates the checking process. Basically, we compare an array with another array and push the boolean result to another array. Simple as that.

In the code above, answers and userAnswers are the global variables we declared earlier. While the former is initialized and assigned a value early on, the latter won't be modified until the last minute i.e. when the final quiz question has been answered.

We merely loop through the array and for each element, we check the expected answer against the user's answer. If everything checks out, push a value of true to our result array. Else, push false.

When the evaluation has been completed, we return the result array so that it can be analyzed later.


Hooking up the Event Handlers

1
 
2
$('.btnStart').click(function(){ 
3
    $(this).parents('.questionContainer').fadeOut(500, function(){ 
4
        $(this).next().fadeIn(500, function(){ progressKeeper.show(); }); 
5
    }); 
6
		 return false; 
7
});

First, let's do the initial intro slide. Remember that all we're doing is display an image that is wrapped by an anchor? That's the anchor we're hooking the above event upto.

Essentially, we're hiding the parent of the clicked link element and then fading in the immediate sibling of the parent.

If you noticed that we aren't adding in each of these lines separately, good. You're paying attention. In the method above, we're passing the next step of the process as the callback to the animation function. This way, each of these animations happens one after the other instead of simultaneously which is the default behavior. This lets us create a smooth interface effect.

1
 
2
$('.btnPrev').click(function(){ 
3
		notice.hide(); 
4
    $(this).parents('.questionContainer').fadeOut(500, function(){ 
5
        $(this).prev().fadeIn(500) 
6
    }); 
7
    progress.animate({ width: progress.width() - Math.round(progressWidth/questionLength), }, 500 ); 
8
		 return false; 
9
});

The above code handles the previous button. The slider functionality is pretty similar. Hide the parent container and fade in the next element in the tree. Basically the same code as in the previous section but with the direction reversed.

With that done, we're tackling the progress bar next. What we're doing here is merely animating the width of the progress bar. No big calculating here -- divide the width of the progress bar by the number of question.

Since this is the previous button, we'll need to subtract the fraction from the total current width of the bar which is what we're doing here. May look a little complicated but trust me, it's fairly simple.

1
 
2
$('.btnNext').click(function(){ 
3
		var tempCheck = $(this).parents('.questionContainer').find('input[type=radio]:checked'); 
4
    if (tempCheck.length == 0) { 
5
         notice.fadeIn(300);return false; 
6
    } 
7
		 notice.hide(); 
8
    $(this).parents('.questionContainer').fadeOut(500, function(){ 
9
        $(this).next().fadeIn(500); 
10
    }); 
11
    progress.animate({ width: progress.width() + Math.round(progressWidth/questionLength), }, 500 ); 
12
		 return false; 
13
});

We have a few more things going on here so pay attention.

First up, we're creating a quick variable and assigning it an array of all radio buttons that have been checked. The input[type=radio]:checked selector helps us do this with minimal fuss.

We can now check the length of this array. If it's zero it means that the user hasn't selected an option and so we can show an error notice chiding the user for this. Which is what is happening inside the if statement. We immediately exit out of the function by using return false.

If we're past the previous step, it's time to proceed. We can now hide the notice, if it has been displayed before.

The slider logic again comes into play -- hide the current container and fade into the next container. We've seen it a number of time already and I don't think I need to rehash it.

Finally, we're handling the progress bar. Similar to the last block, we're calculating the additional width and then add it to the current width of the progress bar. Keep in mind that in the previous block, we subtracted it from the current width. In this block, we're adding it because we're moving to the next question and thus the progress bar forges ahead.


Gathering the User's Answers

1
 
2
$('.btnShowResult').click(function(){ 
3
// Stuff goes in here 
4
});

Ahh, the prodigal event handler that's at the heart of everything. We'll split the process into two parts:

  • Gathering data
  • Evaluating and displaying the results

We're going to tackle the first in this section. Keep in mind that all the JavaScript below goes in the handler above.

1
 
2
var tempCheck = $(this).parents('.questionContainer').find('input[type=radio]:checked'); 
3
if (tempCheck.length == 0) { 
4
     notice.fadeIn(300);return false; 
5
} 
6
var tempArr = $('input[type=radio]:checked'); 
7
for (var i = 0, ii = tempArr.length; i < ii; i++) { 
8
    userAnswers.push(tempArr[i].getAttribute('data-key')); 
9
}

The first few lines should appear very similar. It's because those lines are borrowed directly from the next button's handler. We're checking whether an option has been selected and if not, displaying an error message.

Once we've checked for monkey business, we basically creating an array of all checked checkboxes. We're then looping through the array and capturing the data-key attribute of each element. Remember these? We added these to the radio buttons during the HTML phase and point to the position of the checkbox from an alphabetic perspective. That is, the first option is a, second is b and so on.

What we're doing here is simply gathering the selected answers. Finding out the selected checkbox using the index method is an easier way, in retrospect but this is the way I used in the original codebase and that's what I'm sticking with today.

We push these values to the userAnswers global [within our scope] variable to be evaluated later.


Evaluating the Results

Now that we've gathered our data, we can now quickly analyze and display the results. Let's handle this in smaller chunks.

1
 
2
progressKeeper.hide(); 
3
var results = checkAnswers(),  
4
	 		  resultSet = '', 
5
			  trueCount = 0, 
6
			  answerKey = ' Answers <br />', 
7
			  score;

Since we're at the business end of things, we're hiding the progress bar. No need for it now.

We're also creating a bunch of variables to help us keep track of things internally. The variable results holds the results array that checkAnswers returns. We'll use it to render the final screen. The purpose of the rest of 'em should be apparent shortly.

1
 
2
for (var i = 0, ii = results.length; i &lt; ii; i++){ 
3
	if (results[i] == true) trueCount++; 
4
	resultSet += '<div class="resultRow"> Question #' + (i + 1) + (results[i]== true ? "<div class='correct'><span>Correct</span></div>": "<div class='wrong'><span>Wrong</span></div>") + "</div>"; 
5
	answerKey += (i+1) +" : "+ answers[i] +' &nbsp;  &nbsp;  &nbsp;   '; 
6
} 
7
score =  roundReloaded(trueCount / questionLength*100, 2);

Now that we have the data, let's do some nifty stuff with it. First, we loop through the results to find out the number of questions that the user has gotten right. We'll use this number to calculate the score later.

Next, we'll take it upon ourselves to render the spiffy looking results. Since we're already in the loop, we're going to use it to render everything else. We display the question number and depending on whether the user got that particular question right, place different HTML inside it. Remember, the CSS for the correct and wrong classes? They're being used here.

Since we'll need to display the answer key, we're using the same loop to step through the answers array and display the correct answer.

And finally, we're getting the rounded up score using the roundReloaded function we created earlier and storing the value in the score variable.


Displaying the Results

The meat of our work is done. We'll just need to wrap a few things up and display the results.

1
 
2
answerKey = "<div id='answer-key'>" + answerKey + "</div>"; 
3
resultSet = '<h2 class="qTitle">' +judgeSkills(score) + ' You scored '+score+'%</h2>' + resultSet + answerKey; 
4
$('#resultKeeper').html(resultSet).show(); 
5
	 $(this).parents('.questionContainer').fadeOut(500, function(){ 
6
    $(this).next().fadeIn(500); 
7
}); 
8
return false;

Very simple things going on here. First up, we wrap the value of answerKey with a div with an ID of answer-key to style it better.

Next up, we create the title of the result screen. We use the judgeSkills method to create an appropriate comments followed by some boilerplate to mention the score. We prepend these values to resultSet and to the final string add the answerKey

This concludes the final HTML that needs to be placed inside the results screen. We merely replace the HTML using our pre-generated HTML. With everything now in place, we fade the penultimate slide out and fade in the result screen.


Final Bits of Housekeeping

We have a few simple bits of housekeeping that we'll need to wrap things up.

1
 
2
progressKeeper.hide(); 
3
notice.hide(); 
4
$("#main-quiz-holder input:radio").attr("checked", false);

During initialization, on the splash screen, we have no need for the progress bar or the error message. Let's go ahead and hide it initially. Also, Firefox, for some reason, tends to 'remember' answers so let's erase that completely -- each checkbox is unselected when a page is refreshed.

1
 
2
$('.answers li input').click(function() { 
3
	$(this).parents('.answers').children('li').removeClass("selected"); 
4
	$(this).parents('li').addClass('selected'); 
5
});

Here's a little something to light up the selected option. Pay a little attention because things are a little dicey here.

When a checkbox is selected, we're traversing to the parent list element and removing the selected class from all its child li elements. After that, we're giving the clicked check box's parent a selected class so it shines up bright and blue.

And finally, to complete the slider functionality you'll need to hide all but the first slide. You can use JavaScript to do this or the easier CSS way -- add a display:none declaration to all but the first slide. That's exactly what the hide class does in the demo.


What We've Built





Wrapping up and a Friendly Plug

Phew! That was quite long, wasn't it? I see a sleezy joke there but I'll refrain!

If you enjoyed the quiz engine that we built today, I built an even more advanced version. One with answer reviews on the result page, social sharing, question counters and much more. It's so good that even the Tuts+ sites are going to use it!

Have a quick look at jQuizzy, my new quiz engine. You'll love it, I promise!

Anywho, we're finished here. We looked at creating a quiz engine, from scratch, covering all aspects from the HTML to the CSS to the JavaScript. We looked at nifty techniques to style elements and to program interaction through JavaScript. Hopefully, you found this interesting and useful.

If you run into any issues, leave me a comment. Thank you so much for reading!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.