Hi there just looking for some helpful advice on making ordering/sorting quiz in HTML5/JQuery.
Quite simply want to present a set of steps arranged in random order on the page and the user has to sort them to make the correct order. I have managed to find an example ‘somewhere’ that uses the jquery library and jquery-ui-1.8.5.custom.min.js file and calls the following javascript on the page:
<script type="text/javascript" src="../scripts/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="../scripts/jquery-ui-1.8.5.custom.min.js"> </script>
<script type="text/javascript">
var correctOrder = new Array();
var liItems = new Array();
$(function() {
$("#sortable").sortable({placeholder: 'ui-state-highlight'});
$("#sortable").disableSelection();
var ul = document.getElementById('sortable');
var li = ul.getElementsByTagName("li");
for(var i = 0; i < li.length; i++){
correctOrder.push(li[i].innerHTML);
liItems.push(li[i]);
}
});
(function($){
$.fn.shuffle = function() {
return this.each(function(){
var items = $(this).children();
return (items.length)
? $(this).html($.shuffle(items))
: this;
});
}
$.shuffle = function(arr) {
for(
var j, x, i = arr.length; i;
j = parseInt(Math.random() * i),
x = arr[--i], arr[i] = arr[j], arr[j] = x
);
return arr;
}
})(jQuery);
function resetForm(){
$('#sortable').shuffle();
for(var i = 0;i < liItems.length; i++){
liItems[i].className = "";
}
}
function checkForm(){
var ul = document.getElementById('sortable');
var li = ul.getElementsByTagName("li");
for(var i = 0;i < li.length; i++){
if(li[i].innerHTML != correctOrder[i]){
li[i].className = "incorrect";
}else{
li[i].className = "correct";
}
}
}
</script>
This code seems to work ok but does not randomise the order of the list items successfully (body html is just div that has unordered class in it with id ‘sortable’. I tried to throw in the reset function into the initialing code but that just randomises the order and the answers which is definitely what i don’t want. Simply when a user goes to the page and just clicks ‘submit’ – all the answers will be correct because it did not randomise the list items.
Hope this makes sense, I’m a bit of a noob at JS and I really want to move away from Flash and ActionScript as it has its limitations.
Thanks
Try this to shuffle:
Demo: http://jsbin.com/ibebav/1/edit (ctrl + enter to refresh)
This should get you close to your objective. Also I’d suggest if you use jQuery then use it fully, don’t mix regular DOM and jQuery or it’ll get confusing.