This repository has been archived by the owner on Feb 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.jeasyquiz.core.js
executable file
·905 lines (755 loc) · 22.5 KB
/
jquery.jeasyquiz.core.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
/**
* jQuery plugin : jEasyQuiz
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* @package jEasyQuizz
* @version alpha 1
*/
/**
* @TODO MultipleAnswers.check() when correct and incorrect answers are checked
* @TODO feedback par fonction
* @TODO CSS
*/
(function($)
{
/**
* jEasyQuiz default settings
*/
var settings = {
// main options
source: '', // URL of the file containing the exercises' data
data: {}, // data to send to the source file
requestMethod: 'get', // source file request method (MUST BE either 'get' or 'post')
media: false, // whether or not media files (audio|video) are used in the quizz
// classes of the various containers
loading: 'quizz_loading', // the class of the element containing the loading informations
title: 'quizz_title', // the class of the title container
statement: 'quizz_statement', // the class of the statement container
score: 'quizz_score', // the class of the score container
feedback: 'quizz_feedback',
content: 'quizz_exercise', // the class of the exercise' data container
actionBar: 'quizz_action_bar', // the class of the action bar, containing the buttons
dragContainer: 'quizz_drags', // the class of the element that will contain the draggable elements
dropContainer: 'quizz_drops', // the class of the element that will contain the droppable elements
// buttons and inputs
btnNext: 'quizz_btn_next', // the class of the 'Next' button
btnGo: 'quizz_btn_go', // the class of the 'GO' button
btnCheck: 'quizz_btn_check', // the class of the 'Check' button
inputName: 'quizz_word_answer', // the name attribute to use on the radio inputs
// CSS classes (style can be personnalized int jeasyquiz.css)
answerClass: 'quizz_answer', // the class to add to every answer choice
answerClassPicked: 'quizz_picked', // the class to add to an answer when the user selects it
answerClassCorrect: 'quizz_correct', // the class to add to the picked answer if it's correct
answerClassWrong: 'quizz_wrong', // the class to add to the picked answer if it's wrong
missingLabelClass:'quizz_missing', // the class to add labels of the Missing exercises
draggableClass: 'quizz_draggable', // the class to add to the draggable elements
droppableClass: 'quizz_droppable', // the class to add to the droppable elements
feedbackClassOk: 'quizz_feedback_ok',
feedbackClassWrong: 'quizz_feedback_wrong',
// score infos
initialScore: 0, // the initial score when begining the quizz
scoreIncrease: 1, // the amount of points to add to the current score when a good answer is chosen on first attempt
// directories & URLs
imagesDir: 'images/', // the directory to load the images from
audioDir: 'audio/', // the directory to load the audio files from
// misc
feedbackMessageOk: 'Good answer !', // the default feedback message to show on a good answer
feedbackMessageWrong: 'Bad answer...', // the default feedback message to show on a bad answer
eventNamespace: 'jeasyquiz', // a namespace to use for all the events related to the quizz
blankElement: 'span', // the element containing the blank placeholder
endHandler: function(score, time, percent) // default end of the quiz handler
{
alert('Final score: ' + score + "\n"
+ 'Total time: ' + time.h + ':' + time.m + ':' + time.s + "\n"
+ 'Percentage of correct answers: ' + percent + '%');
}
};
/**
* Basic exercise.
* The user has to pick one only answer among a set of several ones.
*
* @param source The raw xml source
*/
function Exercise(source)
{
var $source = $(source);
this.title = $source.find('title').text();
this.questions = $source.find('question');
this.currentQuestion = -1;
this.firstAttempt = true;
this.lastQuestion = this.questions.length-1;
this.input_type = 'radio';
}
Exercise.prototype =
{
/**
* Get the title of the exercise
*
* @return String
*/
getTitle: function()
{
return this.title;
},
/**
* return the current question (statement + answer) at the specified index
* or the current question if no parameter supplied
*
* @param index the index of the question that has to be returned
*
* @return the question as a jQuey object
*/
getQuestion: function(index)
{
if(arguments.length == 0)
{
index = this.currentQuestion;
}
else
{
index = parseInt(index);
}
return $(this.questions[index]);
},
/**
* return the answers for the current question
*
* @return Array
*/
getAnswers: function(type)
{
var selector = 'answer';
if(type && type.length > 1)
{
selector += '[type="' + type + '"]';
}
return this.getQuestion().find(selector);
},
/**
* return the statement of the question at the specified index
* or the current question if no parameter supplied
*
* @param index the index of the question from which the statement has to be returned
*
* @return string
*/
getStatement: function(index)
{
if(arguments.length == 0)
{
index = this.currentQuestion;
}
return (1+index) + '. ' + this.getQuestion(index).find('statement').text();
},
/**
* Get the content to display for the current question
*
* @return DOMFragment
*/
getContent: function()
{
// cache the document var
var d = document;
var answersContainer = d.createElement('ol');
var answers = this.getAnswers().find('choice');
var len = answers.length;
var answer = null;
var input = null;
var label = null;
var i = 0;
// create a <li> element for each answer
// and add it to the container previously created
for(i; i<len; i++)
{
input = d.createElement('input');
label = d.createElement('label');
answer = d.createElement('li');
input.type = this.input_type;
input.name = settings.inputName;
$(input).data('type', answers[i].getAttribute('type'));
label.className = settings.missingLabelClass + ' ' + settings.answerClass;
label.appendChild(input);
label.appendChild(d.createTextNode(answers[i].getAttribute('label')));
answer.appendChild(label);
answersContainer.appendChild(answer);
}
return answersContainer;
},
/**
* return an array containing all the questions of the exercise
*
* @return Array
*/
getTotalQuestions: function()
{
return this.questions.length;
},
/**
* Get the feedback relative to the chosen answer.
*
* @return string
*/
getFeedback: function()
{
var index = _data.elements.content.find('.' + settings.answerClassPicked).parents('li').index();
var elem = null;
if(index > -1)
{
elem = this.getAnswers().find('choice')[index];
if(elem)
{
return elem.getAttribute('feedback');
}
}
return '';
},
/**
* Get the index of the next question or false if there's no next question
* i.e. if this question was the last one.
*
* @return Number | Boolean
*/
nextQuestion: function()
{
if(this.currentQuestion < this.lastQuestion)
{
this.firstAttempt = true;
return this.currentQuestion++;
}
return false;
},
/**
* return true if it's the first time the user answsers this question, false if not
*
* @return Boolean
*/
isFirstAttempt: function()
{
return this.firstAttempt;
},
/**
* Check if the answer if correct or not
*
* @return Boolean
*/
check: function()
{
var result = null;
if(this.firstAttempt)
{
this.firstAttempt = false;
}
result = _data.elements.content.find('input[name="' + settings.inputName + '"]:checked');
return result.data('type') == 'true';
},
/**
* Return a Boolean meaning if the exercise if finished or not.
*
* @return Boolean
*/
isFinished: function()
{
return (this.currentQuestion == this.lastQuestion);
}
}
/**
* PicturePicking exercise.
* The user has to pick a picture that matches a text description
* or a situation described in an audio extract.
*
* @param source The raw xml source
*/
function PicturePicking(source)
{
Exercise.call(this, source);
this.images = $(source).find('image');
}
PicturePicking.prototype = new Exercise();
PicturePicking.prototype.getContent = function ()
{
var len = this.images.length;
var container = null;
var img = null;
var i = 0;
if(!(this.currentQuestion))
{
container = document.createDocumentFragment();
for(i; i<len; i++)
{
img = new Image();
img.src = settings.imagesDir + this.images[i].getAttribute('src');
$(img).data('match', this.images[i].getAttribute('id'));
img.alt = this.images[i].textContent;
img.className = settings.answerClass;
//img.setAttribute('title', images[i].textContent);
container.appendChild(img);
}
}
_data.elements.content.find('img.' + settings.answerClass)
.removeClass(settings.answerClassPicked + ' ' + settings.answerClassCorrect + ' ' + settings.answerClassWrong);
return container;
};
PicturePicking.prototype.check = function()
{
if(this.firstAttempt)
{
this.firstAttempt = false;
}
return (_data.elements.content.find('img.' + settings.answerClass + '.' + settings.answerClassPicked)
.data('match') == this.getQuestion().find('choice').attr('match'));
};
/**
* DragAndDrop exercise.
* The user has to reorder a set of elements to match another set of elements
*
* @param source The raw xml source
*/
function DragAndDrop(source)
{
Exercise.call(this, source);
this.rightOrder = '';
}
DragAndDrop.prototype = new Exercise();
DragAndDrop.prototype.getContent = function()
{
// cache the document var
var d = document;
var dragContainer = d.createElement('ol');
var dropContainer = d.createElement('ol');
var container = d.createDocumentFragment();
var drags = this.getAnswers('drag').find('choice');
var drops = this.getAnswers('drop').find('choice');
var len = drags.length;
var width = _data.elements.content.width()/2 - 11
var drag = null;
var drop = null;
var i = 0;
dragContainer = $(dragContainer).addClass(settings.dragContainer)
.css({
'padding': '0 0 0 10px',
'float': 'left',
'width': width
});
dropContainer = $(dropContainer).addClass(settings.dropContainer)
.css({
'padding': '0 0 0 10px',
'float': 'left',
'width': width
});
// create and add every elements where the draggables can be dropped (= droppable)
for(i; i<len; i++)
{
// create a list item
drop = d.createElement('li');
drop = $(drop).addClass(settings.droppableClass)
//.data('id', drops[i].getAttribute('id'))
.text(drops[i].getAttribute('label'));
// build the rightOrder attribute
this.rightOrder += '' + drops[i].getAttribute('id') + '#';
// add it to its container, with the data fetched before
dropContainer.append(drop);
}
len = drags.length;
// create and add every draggable elements to the drag global container
for(i=0; i<len; i++)
{
// create a list item
drag = d.createElement('li');
// add it to its container, with all the data fetched before
dragContainer.append($(drag).addClass(settings.draggableClass)
.data('match', drags[i].getAttribute('match'))
.text(drags[i].getAttribute('label')));
}
dragContainer.sortable({
containment: 'parent',
tolerance: 'pointer',
axis: 'y'
}).disableSelection();
// add the drags' and drops' container to the container we return
container.appendChild(dropContainer[0]);
container.appendChild(dragContainer[0]);
container.appendChild($('<hr />', {'style': 'float:none;clear:both;height:0;visibility:hidden;'})[0]);
this.rightOrder = this.rightOrder.split('#');
return container;
};
DragAndDrop.prototype.check = function()
{
var drags = _data.elements.content.find('.' + settings.dragContainer + ' li');
//var drops = _data.elements.content.find('.' + settings.dropContainer + ' li');
var correct = true;
var currentLi = null;
var len = drags.length;
var index = 0;
var i = 0;
if(this.firstAttempt)
{
this.firstAttempt = false;
}
for(i; i<len; i++)
{
currentLi = drags.eq(i);
index = currentLi.index();
if(currentLi.data('match') != this.rightOrder[index])
{
correct = false;
}
else
{
currentLi.addClass(settings.answerClassCorrect);
}
}
return correct;
};
/**
* MultipleAnswers exercise.
* The user has to pick the correct answers relative to the statement.
*
* @param source The raw xml source
*/
function MultipleAnswers(source)
{
Exercise.call(this, source);
this.input_type = 'checkbox';
}
MultipleAnswers.prototype = new Exercise();
MultipleAnswers.prototype.check = function()
{
var answers = _data.elements.content.find('label.' + settings.answerClass + ' input[type="checkbox"]');
var len = answers.length;
var check = true;
var $answer = null;
var i = 0;
if(this.firstAttempt)
{
this.firstAttempt = false;
}
for(i; i<len; i++)
{
$answer = $(answers[i]);
switch(true)
{
case ($answer.data("type") == "false" && $answer.prop("checked")) :
$answer.removeProp("checked");
case ($answer.data("type") == "true" && !$answer.prop("checked")) :
check = false;
break;
}
}
return check;
};
/**
* Internal data
*/
var _data = {
exercises: [],
score: 0,
maxScore: 0,
totalQuestions: 0,
currentExercise: 0,
currentQuestion: 0,
/**
* Holds several elements we manipulate a lot
*/
elements: {
container: null,
title: null,
statement: null,
content: null,
actionBar: null,
score: null,
btnCheck: null,
btnNext: null,
feedback: null
}
};
/**
* Private methods unavailable for end-users
*/
var privateMethods = {
getCurrentExercise: function()
{
return _data.exercises[_data.currentExercise];
},
/**
* Initialize the quiz
* @param options An option object
*/
init: function(options)
{
$.extend(settings, options);
return this.each(function()
{
var data = $(this).data('jeasyquiz');
// if the plugin hasn't been initialized yet
if (!data)
{
if(!settings.source || settings.source === '')
{
$.error('Unable to initialize the quiz because no source of data was supplied.');
}
else
{
// data settings
_data.elements.container = $(this);
// show the loading feedback and hide the "go" button
_data.elements.container.find('.' + settings.loading).show()
.end().find('.' + settings.btnGo).hide();
// hide the action bar and store it in the _data object
_data.elements.actionBar = _data.elements.container.find('.' + settings.actionBar).hide();
if(_data.elements.container.find('.' + settings.title).length == 0)
{
_data.elements.actionBar.before($('<h2 />', {
"class": settings.title
}));
}
if(_data.elements.container.find('.' + settings.statement).length == 0)
{
_data.elements.actionBar.before($('<h3 />', {
"class": settings.statement
}));
}
if(_data.elements.container.find('.' + settings.content).length == 0)
{
_data.elements.actionBar.before($('<div />', {
"class": settings.content
}));
}
$.ajax({
url: settings.source,
async: true,
type: settings.requestMethod,
data: (settings.data),
dataType: 'xml',
success: function(data)
{
privateMethods.processData($(data).find('exercise'));
_data.maxScore = _data.totalQuestions*settings.scoreIncrease + settings.initialScore;
// set the initial score
publicMethods.updateScore(settings.initialScore);
_data.elements.container.find('.' + settings.loading)
.hide(500).end()
.find('.' + settings.btnGo).show(500);
//settings.data = data;
},
error: function()
{
$.error('Unable to initialize the quiz because the data source could not be reached.');
}
});
// populate the data
_data.score = settings.initialScore;
_data.elements.title = _data.elements.container.find('.' + settings.title);
_data.elements.statement = _data.elements.container.find('.' + settings.statement);
_data.elements.content = _data.elements.container.find('.' + settings.content);
_data.elements.feedback = _data.elements.container.find('.' + settings.feedback);
_data.elements.score = _data.elements.container.find('.' + settings.score);
_data.elements.btnNext = _data.elements.actionBar.find('.' + settings.btnNext);
_data.elements.btnCheck = _data.elements.actionBar.find('.' + settings.btnCheck);
/**
* Buttons Events binding
*/
// "go" button
_data.elements.container.find('.' + settings.btnGo)
.bind('click.' + settings.eventNamespace , function()
{
// hide the loader and the button
_data.elements.container.find('.' + settings.loading).hide();
$(this).hide();
publicMethods.nextQuestion();
// show the other elements
_data.elements.title.show();
_data.elements.statement.show();
_data.elements.content.show();
_data.elements.actionBar.show();
});
// "check" button
_data.elements.btnCheck.live('click.' + settings.eventNamespace, function()
{
publicMethods.checkAnswer();
});
// "next" button
_data.elements.btnNext.live('click.' + settings.eventNamespace, function()
{
publicMethods.nextQuestion();
});
/**
* Answer elements events binding
*/
_data.elements.content.find('.' + settings.answerClass)
.live('click.' + settings.eventNamespace, function()
{
_data.elements.content.find('.' + settings.answerClass)
.removeClass(settings.answerClassPicked);
$(this).addClass(settings.answerClassPicked);
});
}
// set the data to prevent the plugin from beeing accidently re-initialized
data = _data;
}
});
},
/**
* Build the exercises from raw xml data
* @param rawExercises The raw data
*/
processData: function(rawExercises)
{
var len = rawExercises.length;
var i = 0;
for(i; i<len; i++)
{
//switch (rawExercises.eq(i).attr('type'))
switch (rawExercises[i].getAttribute('type'))
{
case 1 :
case '1' :
case 'PicturePicking' :
case 'pp' :
_data.exercises.push(new PicturePicking(rawExercises[i]));
_data.totalQuestions += _data.exercises[i].getTotalQuestions();
break;
case 2 :
case '2' :
case 'MissingWord' :
case 'mw' :
case 3 :
case '3' :
case 'AudioMatching' :
case 'am' :
_data.exercises.push(new Exercise(rawExercises[i]));
_data.totalQuestions += _data.exercises[i].getTotalQuestions();
break;
case 4 :
case '4' :
case 'MultipleAnswers' :
case 'ma' :
_data.exercises.push(new MultipleAnswers(rawExercises[i]));
_data.totalQuestions += _data.exercises[i].getTotalQuestions();
break;
case 5 :
case '5' :
case 'dd' :
case 'DragAndDrop' :
case 'dnd' :
_data.exercises.push(new DragAndDrop(rawExercises[i]));
_data.totalQuestions += _data.exercises[i].getTotalQuestions();
break;
default:
break;
}
}
}
};
/**
* Methods the user can call
*/
var publicMethods = {
/*nextExercise: function()
{
_data.currentExercise++;
_data.currentQuestion = -1;
publicMethods.nextQuestion();
},*/
/**
* Display the next question
*
* @return this
*/
nextQuestion: function()
{
var currentExercise = privateMethods.getCurrentExercise();
var newContent = null;
// hide the "next" button
_data.elements.btnNext.hide();
// hide the feedback
_data.elements.feedback.hide();
// show the "check" button
_data.elements.btnCheck.show();
//if(currentExercise.isFinished())
// if there is no next question
if(currentExercise.nextQuestion() === false)
{
// go to the next exercise
_data.currentExercise++;
_data.currentQuestion = -1;
currentExercise = privateMethods.getCurrentExercise();
currentExercise.nextQuestion();
}
// update the title
_data.elements.title.text(currentExercise.getTitle());
// update the statement
_data.elements.statement.html(currentExercise.getStatement());
// get the new content to display
newContent = currentExercise.getContent();
// update the content if necessary
if(newContent !== null)
{
_data.elements.content.html(newContent);
}
return _data.elements.container;
},
/**
* Check the if the answer given by the user is correct and display the appropriate feedback
*
* @return _data.elements.container;
*/
checkAnswer: function()
{
var currentExercise = privateMethods.getCurrentExercise();
var feedback = '';
var feedbackClass = '';
var firstAttempt = currentExercise.isFirstAttempt();
if(currentExercise.check() === true)
{
if(firstAttempt)
{
publicMethods.updateScore();
}
feedbackClass = settings.feedbackClassOk;
feedback = currentExercise.getFeedback() || settings.feedbackMessageOk;
}
else
{
feedbackClass = settings.feedbackClassWrong;
feedback = currentExercise.getFeedback() || settings.feedbackMessageWrong;
}
// update the feedback and show it
_data.elements.feedback
.removeClass(settings.feedbackClassOk + ' ' + settings.feedbackClassWrong)
.addClass(feedbackClass).text(feedback).hide().fadeIn();
// show the "next button"
_data.elements.btnNext.fadeIn();
return _data.elements.container;
},
/**
* Update the score
* @return _data.elements.container;
*/
updateScore: function(newScore)
{
if(arguments.length == 0)
{
_data.score += settings.scoreIncrease;
newScore = _data.score;
}
_data.elements.score.text(newScore + ' / ' + _data.maxScore);
return _data.elements.container;
}
};
$.fn.jEasyQuiz = function(params)
{
if (publicMethods[params])
{
return publicMethods[params].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof params === 'object' || !params)
{
return privateMethods.init.apply(this, arguments);
}
else
{
return $.error('Method ' + params + ' does not exist on jQuery.jEasyQuiz');
}
};
})(jQuery);