draggame.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. displayedQuestions = null;
  2. displayedAnswers = null;
  3. function setupDraggame(questions, answers) {
  4. var dropzones = $("#dropzones");
  5. dropzones.empty();
  6. for (var i = 0; i < questions.length; i++) {
  7. var $nz = document.createElement("div");
  8. $nz.setAttribute("id", "qdz" + i);
  9. $nz.setAttribute("class", "question-dropzone");
  10. $nz.setAttribute("ondragover", "allowDrag(event)");
  11. $nz.setAttribute("ondrop", "drop(event)");
  12. //$nz.textContent = questions[i];
  13. $nz.innerHTML = "<div style='float: left; max-width: 70%; text-align: left;'>" + questions[i] + "</div>";
  14. dropzones.append($nz);
  15. }
  16. var qsource = $("#qdz-source");
  17. qsource.empty();
  18. for (var i = 0; i < answers.length; i++) {
  19. var $de = document.createElement("p");
  20. $de.setAttribute("id", "qde" + i);
  21. $de.setAttribute("class", "question-dropelement");
  22. $de.setAttribute("draggable", "true");
  23. $de.setAttribute("ondragstart", "drag(event)");
  24. $de.textContent = answers[i];
  25. qsource.append($de);
  26. }
  27. displayedQuestions = questions;
  28. displayedAnswers = answers;
  29. }
  30. function getDragAnswers() {
  31. answers = [];
  32. var dropzones = $("#dropzones").children();
  33. for(var i = 0; i < dropzones.length; i++) {
  34. var dz = dropzones[i];
  35. if (dz.id.startsWith("qdz")) {
  36. var q_id = parseInt(dz.id.substring(3));
  37. var dropelements = $("#" + dz.id).children();
  38. for(var j = 0; j < dropelements.length; j++) {
  39. var de = dropelements[j];
  40. if (de.id.startsWith("qde")) {
  41. var a_id = parseInt(de.id.substring(3));
  42. if (q_id != NaN && a_id != NaN) {
  43. //answers[displayedQuestions[q_id]] = displayedAnswers[a_id];
  44. answers.push([displayedAnswers[a_id], displayedQuestions[q_id]]);
  45. }
  46. }
  47. }
  48. }
  49. }
  50. return answers;
  51. }
  52. function allowDrag(e) {
  53. e.preventDefault();
  54. }
  55. function drag(e) {
  56. e.dataTransfer.setData("id", e.target.id);
  57. }
  58. function drop(e) {
  59. e.preventDefault();
  60. var id = e.dataTransfer.getData("id");
  61. var target = e.target;
  62. while (!target.classList.contains("question-dropzone") && !target.classList.contains("question-dropsource"))
  63. target = target.parentNode;
  64. var occupyingDrop = target.querySelector(".question-dropelement");
  65. var element = document.getElementById(id);
  66. if (occupyingDrop != null && !target.classList.contains("question-dropsource")) {
  67. element.parentNode.appendChild(occupyingDrop);
  68. }
  69. target.appendChild(element);
  70. }