A Drag & Drop Game using jQuery

Hi. Today we will create a drag and drop game using jQuery drag drop functions. We will create two boxes. From one box we need to drag the content box and drop it to another box. We will use a sortable function and its events. I hope you will like this game.

Please see this article in my blog.

Background

For the last Independence day for India, I thought to create a game related to the word “India”. I created and hosted it in my website.

Play the game

You can play the game here.

Using the code

First we will create an html5 page as follows.

  1. <!DOCTYPE html>  
  2. <html>  
  3.    <head>  
  4.       <title>Find INDIA Game - Sibeesh Passion</title>     
  5.    </head>  
  6.    <body id="body">  
  7.    </body>  
  8. </html>  

And now we will set style to the body. To set the background image fit to the screen we will use the following styles.

  1. #body {  
  2.    background: url("http://sibeeshpassion.com/content/images/indian%20flag%20banner.jpg") no-repeat center center fixed;  
  3.    -webkit-background-size: cover;  
  4.    -moz-background-size: cover;  
  5.    -o-background-size: cover;  
  6.    background-size: cover;  
  7. }  

Now we can see the page as follows.

Make Image Fit To The Screen

Fit the Image To The Screen

Since we will create a client-side game, it is necessary to load the jQuery and jQuery UI reference.

  1. <script src="jquery-2.0.2.min.js"></script>  
  2. <script src="jquery-ui.js"></script>  

Next we will create the dragable contents as follows.

  1. <div class="dragDiv">  
  2.     <div id="dragDivInner">  
  3.         <div myid="1" class="droppable" myval="I"></div>  
  4.         <div myid="2" class="droppable"></div>  
  5.         <div myid="3" class="Notdroppable"></div>  
  6.         <div myid="6" class="droppable"></div>  
  7.         <div myid="7" class="droppable"></div>  
  8.         <div myid="8" class="Notdroppable"></div>  
  9.         <div myid="9" class="droppable" myval="N"></div>  
  10.         <div myid="10" class="Notdroppable"></div>  
  11.         <div myid="11" class="droppable"></div>  
  12.         <div myid="12" class="droppable"></div>  
  13.         <div myid="17" class="droppable"></div>  
  14.         <div myid="18" class="Notdroppable"></div>  
  15.         <div myid="19" class="droppable"></div>  
  16.         <div myid="20" class="Notdroppable" myval="A"></div>  
  17.         <div myid="21" class="droppable"></div>  
  18.         <div myid="22" class="droppable"></div>  
  19.         <div myid="23" class="Notdroppable"></div>  
  20.         <div myid="24" class="droppable"></div>  
  21.         <div myid="25" class="Notdroppable" myval="I"></div>  
  22.         <div myid="26" class="droppable"></div>  
  23.         <div myid="27" class="droppable"></div>  
  24.         <div myid="28" class="Notdroppable"></div>  
  25.         <div myid="29" class="droppable"></div>  
  26.         <div myid="30" class="Notdroppable"></div>  
  27.         <div myid="31" class="Notdroppable" myval="D"></div>  
  28.         <div myid="32" class="droppable"></div>  
  29.         <div myid="33" class="droppable"></div>  
  30.         <div myid="34" class="Notdroppable"></div>  
  31.         <div myid="35" class="droppable"></div>  
  32.         <div myid="40" class="Notdroppable"></div>  
  33.     </div>  
  34. </div>    

Now we need to set a div where we can drag contents to it.

  1. <div class="dropDiv">  
  2.    <div id="draggedContent" style="display: none;"></div>  
  3. </div>  

Since it is a game, we must set the game rules also, right?

  1. <div id="gamerules">  
  2.    <ul>  
  3.       <li class="caption">Find "INDIA" Game Rules </li>  
  4.       <li>You can drag and drop any boxes. </li>  
  5.       <li>We have set each letters from "INDIA" in the boxes. It is hidden</li>  
  6.       <li>The game is, you need to find out the letters of "INDIA" by drag and drop the boxes to nearest box</li>  
  7.       <li>Let us play the game now...</li>  
  8.    </ul>  
  9. </div>  

And we will set some styles for those elements.

  1. .dropDiv {  
  2.     border: 1px solid#ccc;  
  3.     width: 25 % ;  
  4.     height: auto;  
  5.     padding: 10px;  
  6.     display: inline;  
  7.     position: absolute;  
  8.     margin - left: 5px;  
  9.     min - height: 265px;  
  10. }.dragDiv {  
  11.     border: 1px solid#ccc;  
  12.     width: 27 % ;  
  13.     height: auto;  
  14.     padding: 10px;  
  15.     float: left;  
  16.     margin - left: 5px;  
  17.     min - height: 265px;  
  18. }#parent {  
  19.     /*border: 1px solid #ccc;*/  
  20.     height: 307px;  
  21.     width: 70 % ;  
  22.     padding: 20px;  
  23. }.droppable {  
  24.     width: 25px;  
  25.     height: 28px;  
  26.     padding: 5px;  
  27.     background - color: green;  
  28.     margin: 3px;  
  29.     float: left;  
  30.     cursor: move;  
  31. }.Notdroppable {  
  32.     width: 25px;  
  33.     height: 28px;  
  34.     padding: 5px;  
  35.     background - color: red;  
  36.     margin: 3px;  
  37.     float: left;  
  38. }#countdiv {  
  39.     margin - top: 10px;  
  40.     float: left;  
  41. }#gamerules {  
  42.     border: 1px solid#ccc;  
  43.     width: 250px;  
  44.     height: 280px;  
  45.     padding: 5px;  
  46.     float: right;  
  47.     margin - left: 5px;  
  48. }.caption {  
  49.     list - style: none;  
  50.     color: green;  
  51.     padding: 5px;  
  52.     font - weight: bold;  
  53. }  

So our page will look such as follows.

Drag And Drop Game


Drag And Drop Game

The next thing to do is to add sortable functionality using jQuery sortable to the div that has the class dropDiv.

  1. $(".dropDiv").sortable({  
  2.    connectWith: '.dropDiv',  
  3.    forcePlaceholderSize: true,  
  4.    forceHelperSize: true,  
  5.    opacity: 0.60,  
  6.    placeholder: 'placeholder',  
  7.    tolerance: 'touch',  
  8.    scroll: false,  
  9.    cancel: '.dropDiv',  
  10.    start: function (event, ui) {  
  11.    },  
  12.    stop: function (event, ui) {  
  13.    },  
  14.    update: function (event, ui) {  
  15.    },  
  16.    receive: function (event, ui) {  
  17.    }  
  18. });  

Please note that we have provided the connectWith property as follows to make the dragable div to be dropped only in the div that has the class dropDiv.

  1. connectWith: '.dropDiv'  

We have also set the property cancel as follows to make the dropped div not dragable from dropDiv.

  1. cancel: '.dropDiv',  

Next we will set draggable for our inner divs.

  1. $('.Notdroppable,.droppable').draggable({  
  2.    connectToSortable: '.dropDiv',  
  3.    containment: "#dropDiv",  
  4.    helper: 'clone',  
  5.    revert: 'invalid'  
  6. });  

Game Insights

As you can see in the HTML of the our dragDiv, we have set an attribute myval for some of the div. So what we will do is, when a user drags a div we will check whether that specific div has that attribute and if it has, the user gets a letter. In this way the user needs to collect 5 letters from the dragDiv.

So in the stop function of sortable we will write some scripts as follows.

  1. stop: function (event, ui) {  
  2.    ++count;  
  3.    if (ui.item.attr('myval')) {  
  4.       $('#draggedContent').show().append(ui.item.attr('myval'));  
  5.    }  
  6.    $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();  
  7.    var res = maxTrial - count;  
  8.    if (res == 0) {  
  9.       $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');  
  10.       $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();  
  11.       } 
  12.    else {  
  13.       $('#countdiv').show().html('You still have ' + res + ' tries');  
  14.    }  
  15.    $('.dropDiv .droppable, .dropDiv .Notdroppable').remove();  
  16.    if ($('#draggedContent').html().length == 5) {  
  17.       alert('You have won the game!!!. Please collect the prize from somewhere ;)');  
  18.       $('#countdiv').show().html('You have won the game!!!. Please collect the prize from somewhere ;)!. Please refresh to start the game again');  
  19.       $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();  
  20.    }  
  21. }  
We are checking whether the inner div has a specific attribute as follows and once we find it, we are removing that from dragDiv.
  1. if (ui.item.attr('myval')) {  
  2.    $('#draggedContent').show().append(ui.item.attr('myval'));  
  3. }  
  4. $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();  

If a user has already has those five letters, we must alert the user, right? We will do this validation in the start function.

  1. start: function (event, ui) {  
  2.    if (count > maxTrial) {  
  3.       $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');  
  4.    } 
  5.    else 
  6.    {  
  7.    }  
  8. }  
 
Drag And Drop Game

Drag And Drop Game

Drag And Drop Game

Drag And Drop Game

If there is no chances left, the user will get a message as follows.

Drag And Drop Game

Drag And Drop Game

Now what to do next? Yes, we need to shuffle the div contents or else the user may find it easy when the tiles are in the same order and the same place.

To shuffle the divs dynamically we will add some scripts as follows.

  1. var parent = $("#dragDivInner");  
  2. var divs = parent.children();  
  3. while (divs.length) {  
  4. parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);  
  5. }  

Next we will disable the right-click and mouse events as follows.

  1. document.onmousedown = function (event) {  
  2.    event = (event || window.event);  
  3.    if (event.keyCode == 123) {  
  4.       return false;  
  5.    }  
  6. }  
  7. document.onkeydown = function (event) {  
  8.    event = (event || window.event);  
  9.    if (event.keyCode == 123) {  
  10.       return false;  
  11.    }  
  12. }  
  13. $(document).on("contextmenu"function (e) {  
  14.    return false;  
  15. });  

We will also disable the F12 key of the keyboard.

  1. document.onkeypress = function (event) {  
  2.    event = (event || window.event);  
  3.    if (event.keyCode == 123) {  
  4.       return false;  
  5.    }  
  6. }  

As every game has some settings, we will also provide some settings.

  1. <div id="gameSettings">  
  2. <br />  
  3. Select Game Level :  
  4. <select id="selectGameLevel">  
  5.    <option value="Easy">Easy</option>  
  6.    <option value="Medium">Medium</option>  
  7.    <option value="Hard">Hard</option>  
  8. </select>  
  9. </div>  

And in the drop down option change, we will decrease the maximum trials allowed.

  1. $("#selectGameLevel").change(function (e) {  
  2.    var selected = $("#selectGameLevel option:selected").val();  
  3.       if (selected == "Easy") {  
  4.          maxTrial = 25;  
  5.       } else if (selected == "Medium") {  
  6.          maxTrial = 15;  
  7.          } else if (selected == "Hard") {  
  8.             maxTrial = 10;  
  9.          }  
  10. }   );  

So our complete page will look like this.

Drag And Drop Game

Drag And Drop Game

Our complete code is as follows.

Complete Code

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title>Find INDIA Game - Sibeesh Passion</title>  
  5.         <script src="jquery-2.0.2.min.js"></script>  
  6.         <script src="jquery-ui.js"></script>  
  7.         <style>    
  8.     #body {  
  9.     background: url("http://sibeeshpassion.com/content/images/indian%20flag%20banner.jpg") no - repeat center center fixed; - webkit - background - size: cover; - moz - background - size: cover; - o - background - size: cover;  
  10.     background - size: cover;  
  11. }.dropDiv {  
  12.     border: 1px solid#ccc;  
  13.     width: 25 % ;  
  14.     height: auto;  
  15.     padding: 10px;  
  16.     display: inline;  
  17.     position: absolute;  
  18.     margin - left: 5px;  
  19.     min - height: 265px;  
  20. }.dragDiv {  
  21.     border: 1px solid#ccc;  
  22.     width: 27 % ;  
  23.     height: auto;  
  24.     padding: 10px;  
  25.     float: left;  
  26.     margin - left: 5px;  
  27.     min - height: 265px;  
  28. }#parent {  
  29.     /*border: 1px solid #ccc;*/  
  30.     height: 307px;  
  31.     width: 70 % ;  
  32.     padding: 20px;  
  33. }.droppable {  
  34.     width: 25px;  
  35.     height: 28px;  
  36.     padding: 5px;  
  37.     background - color: green;  
  38.     margin: 3px;  
  39.     float: left;  
  40.     cursor: move;  
  41. }.Notdroppable {  
  42.     width: 25px;  
  43.     height: 28px;  
  44.     padding: 5px;  
  45.     background - color: red;  
  46.     margin: 3px;  
  47.     float: left;  
  48. }#countdiv {  
  49.     margin - top: 10px;  
  50.     float: left;  
  51. }#gamerules {  
  52.     border: 1px solid#ccc;  
  53.     width: 250px;  
  54.     height: 280px;  
  55.     padding: 5px;  
  56.     float: right;  
  57.     margin - left: 5px;  
  58. }.caption {  
  59.     list - style: none;  
  60.     color: green;  
  61.     padding: 5px;  
  62.     font - weight: bold;  
  63. }#gameSettings {  
  64.     width: auto;  
  65. }  
  66.         </style>  
  67.          < script >  
  68. var count = 0;  
  69. var maxTrial = 25;  
  70. document.onkeypress = function(event) {  
  71.     event = (event || window.event);  
  72.     if (event.keyCode == 123) {  
  73.         return false;  
  74.     }  
  75. }  
  76. document.onmousedown = function(event) {  
  77.     event = (event || window.event);  
  78.     if (event.keyCode == 123) {  
  79.         return false;  
  80.     }  
  81. }  
  82. document.onkeydown = function(event) {  
  83.     event = (event || window.event);  
  84.     if (event.keyCode == 123) {  
  85.         return false;  
  86.     }  
  87. }  
  88. $(function() {  
  89.     $(document).on("contextmenu", function(e) {  
  90.         return false;  
  91.     });  
  92.     var parent = $("#dragDivInner");  
  93.     var divs = parent.children();  
  94.     while (divs.length) {  
  95.         parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);  
  96.     }  
  97.     $("#selectGameLevel").change(function(e) {  
  98.         var selected = $("#selectGameLevel option:selected").val();  
  99.         if (selected == "Easy") {  
  100.             maxTrial = 25;  
  101.         } else if (selected == "Medium") {  
  102.             maxTrial = 15;  
  103.         } else if (selected == "Hard") {  
  104.             maxTrial = 10;  
  105.         }  
  106.     });  
  107.     $('.Notdroppable,.droppable').draggable({  
  108.         connectToSortable: '.dropDiv',  
  109.         containment: "#dropDiv",  
  110.         helper: 'clone',  
  111.         revert: 'invalid'  
  112.     });  
  113.     $(".dropDiv").sortable({  
  114.         connectWith: '.dropDiv',  
  115.         forcePlaceholderSize: true,  
  116.         forceHelperSize: true,  
  117.         opacity: 0.60,  
  118.         placeholder: 'placeholder',  
  119.         tolerance: 'touch',  
  120.         scroll: false,  
  121.         cancel: '.dropDiv',  
  122.         start: function(event, ui) {  
  123.             if (count > maxTrial) {  
  124.                 $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');  
  125.             } else {}  
  126.         },  
  127.         stop: function(event, ui) {  
  128.             ++count;  
  129.             if (ui.item.attr('myval')) {  
  130.                 $('#draggedContent').show().append(ui.item.attr('myval'));  
  131.             }  
  132.             $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();  
  133.             var res = maxTrial - count;  
  134.             if (res == 0) {  
  135.                 $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');  
  136.                 $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();  
  137.             } else {  
  138.                 $('#countdiv').show().html('You still have ' + res + ' tries');  
  139.             }  
  140.             $('.dropDiv .droppable, .dropDiv .Notdroppable').remove();  
  141.             if ($('#draggedContent').html().length == 5) {  
  142.                 alert('You have won the game!!!. Please collect the prize from somewhere ;)');  
  143.                 $('#countdiv').show().html('You have won the game!!!. Please collect the prize from somewhere ;)!. Please refresh to start the game again');  
  144.                 $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();  
  145.             }  
  146.         },  
  147.         update: function(event, ui) {},  
  148.         receive: function(event, ui) {}  
  149.     });  
  150. }); < /script>  
  151.     </head>  
  152.     <body id="body">  
  153.         <div id="gameSettings">  
  154.             <br />    
  155. Select Game Level :    
  156.   
  157.             <select id="selectGameLevel">  
  158.                 <option value="Easy">Easy</option>  
  159.                 <option value="Medium">Medium</option>  
  160.                 <option value="Hard">Hard</option>  
  161.             </select>  
  162.         </div>  
  163.         <div id="parent" style="float: left;">  
  164.             <div class="dragDiv">  
  165.                 <div id="dragDivInner">  
  166.                     <div myid="1" class="droppable" myval="I"></div>  
  167.                     <div myid="2" class="droppable"></div>  
  168.                     <div myid="3" class="Notdroppable"></div>  
  169.                     <div myid="6" class="droppable"></div>  
  170.                     <div myid="7" class="droppable"></div>  
  171.                     <div myid="8" class="Notdroppable"></div>  
  172.                     <div myid="9" class="droppable" myval="N"></div>  
  173.                     <div myid="10" class="Notdroppable"></div>  
  174.                     <div myid="11" class="droppable"></div>  
  175.                     <div myid="12" class="droppable"></div>  
  176.                     <div myid="17" class="droppable"></div>  
  177.                     <div myid="18" class="Notdroppable"></div>  
  178.                     <div myid="19" class="droppable"></div>  
  179.                     <div myid="20" class="Notdroppable" myval="A"></div>  
  180.                     <div myid="21" class="droppable"></div>  
  181.                     <div myid="22" class="droppable"></div>  
  182.                     <div myid="23" class="Notdroppable"></div>  
  183.                     <div myid="24" class="droppable"></div>  
  184.                     <div myid="25" class="Notdroppable" myval="I"></div>  
  185.                     <div myid="26" class="droppable"></div>  
  186.                     <div myid="27" class="droppable"></div>  
  187.                     <div myid="28" class="Notdroppable"></div>  
  188.                     <div myid="29" class="droppable"></div>  
  189.                     <div myid="30" class="Notdroppable"></div>  
  190.                     <div myid="31" class="Notdroppable" myval="D"></div>  
  191.                     <div myid="32" class="droppable"></div>  
  192.                     <div myid="33" class="droppable"></div>  
  193.                     <div myid="34" class="Notdroppable"></div>  
  194.                     <div myid="35" class="droppable"></div>  
  195.                     <div myid="40" class="Notdroppable"></div>  
  196.                 </div>  
  197.                 <div id="countdiv" style="display: none;"></div>  
  198.             </div>  
  199.             <div class="dropDiv">  
  200.                 <div id="draggedContent" style="display: none;"></div>  
  201.             </div>  
  202.             <div id="gamerules">  
  203.                 <ul>  
  204.                     <li class="caption">Find "INDIA" Game Rules </li>  
  205.                     <li>You can drag and drop any boxes. </li>  
  206.                     <li>We have set each letters from "INDIA" in the boxes. It is hidden</li>  
  207.                     <li>The game is, you need to find out the letters of "INDIA" by drag and drop the boxes to nearest box</li>  
  208.                     <li>Let us play the game now...</li>  
  209.                 </ul>  
  210.             </div>  
  211.         </div>  
  212.     </body>  
  213. </html>    

Now let us play the game.

Conclusion

I hope you liked my article. Now please share me your feedback. Thanks in advance.

Kindest Regards,
Sibeesh Venu

Up Next
    Ebook Download
    View all
    Learn
    View all