Join over 55,891 Subscribers Today! FREE UPDATES!
Get The Only Freelancer crash course you will ever need to read!
Almost everyone, at one point during childhood, has played jigsaw puzzles. Today I am going to show you how to create a jigsaw puzzle using jQuery and PHP.
Lets start creating puzzles. I know that you must be waiting to see the puzzle in action. I am not going to keep you guessing. Here is the sample demo of the puzzle and download of tutorial files.
Now you got your wish. So lets move onto creating the puzzle.
First thing we have to do is choose an image for the puzzle. Only jpg images can be used in this example. I am going to use the 1stwebdesigner header image for the puzzle. Once you choose the image it has to be split into smaller images to create the puzzle components.
There are a lot of online tools available for splitting images. But I am going to use my own php code to split the image. The purpose of this tutorial is to make the puzzle. So I am not going to explain the whole PHP code for splitting images. I’ll just explain the necessary configurations.
<?php
$image_file = 'puzzle.jpg';
$src = imagecreatefromjpeg($image_file);
list($width, $height, $type, $attr) = getimagesize($image_file);
$split_size = '150';
$cal_width = $width % $split_size;
$cal_height = $height % $split_size;
if ($cal_width > 0) {
$new_width = intval($width / $split_size) * $split_size + 100;
} else {
$new_width = $width;
}
if ($cal_height > 0) {
$new_height = intval($height / $split_size) * $split_size + 100;
} else {
$new_height = $height;
}
if ($width > 1200) {
$width = 1200;
$new_width = 1200;
}
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($image_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, $image_file, 100);
$x_comp = intval($new_width / $split_size);
$y_comp = intval($new_height / $split_size);
$winning_string = '';
$image_names = '';
$src = imagecreatefromjpeg($image_file);
$dest = imagecreatetruecolor($split_size, $split_size);
for ($y = 0; $y < $y_comp; $y++) {
for ($i = 0; $i < $x_comp; $i++) {
$characters = 'abcdefghijklmnopqrstuvwxyz';
$ran_string = '';
for ($p = 0; $p < 4; $p++) {
$ran_string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
imagecopy($dest, $src, 0, 0, $i * $split_size, $y * $split_size, $split_size, $split_size);
imagejpeg($dest, "images/$ran_string.jpg");
$winning_string .= $ran_string;
$image_names .= $ran_string . ",";
}
}
$image_names = substr($image_names, 0, -1);
$images = explode(',', $image_names);
shuffle($images);
?>
Code Explanation
Now what you have to do is download the tutorial files first. Then copy it to your web server and give necessary permissions to folders. Then open the split.php file and make the changes mentioned above or keep the default values.
Once you execute it in the browser you will get a output like the following.

You should keep both Winning String and Load String as shown in the above screen. Now we are done with the image split. So lets move onto the next section.
I have already created images for our puzzle in the images folder. Now we have to create the puzzle by loading the puzzle images. Before that we need to enable Drag and Drop support using Jquery UI library. So I’ll show you the necessary files to be included.
I have downloaded and included the necessary files of jQuery UI Library in the tutorial files. You can use the following code to include the files related to our tutorial.
<html lang='en'> <head> <title>Jquery Drag and Drop Puzzle</title> <script src="jquery-1.7.2.js" type="text/javascript"></script> <script src="ui/jquery.ui.core.js" type="text/javascript"></script> <script src="ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="ui/jquery.ui.mouse.js" type="text/javascript"></script> <script src="ui/jquery.ui.sortable.js" type="text/javascript"></script> <link rel="stylesheet" href="demos.css"> </head> <body> </body> </html>
In the code you can see the file called jquery.ui.sortable.js. It is used to handle the drag and drop and then sort the items inside the given container. This is called Sortable in Jquery UI library. Once you make an element sortable, you will be able to both drag and drop items inside that element. You can make item sortable using the following code.
Jquery Code for Making Unordered List Sortable
$("#sortable").sortable();
Unordered List with Items
<ul id='sortable'>
<li>Item 1</li>
<li>Item 2</li>
</ul>
Above codes will enable sortable event on all the li items inside the ul container with the id sortable
Basic CSS Styles for Sortable Element
<style type='text/css'>
#sortable { list-style-type: none; margin: 0; padding: 0; }
#sortable li { float: left;}
.msg_text{
text-align: center;
padding: 20px;
font-size: 30px;
text-shadow: 1px 1px 1px rgb(21, 23, 28);
}
</style>

Now I am going to display the image parts as puzzle. We can use the following PHP code with small configurations to load the images. This code is located in puzzle.php file on the project folder. You can run the puzzle.php file in your web server to directly execute the demo. Now get ready with the Winning String we created earlier.
<?php
$image_names = "ilsc,scmz,lsea,derv,logi,eyen,vkxl,ihrx,mwgc,bwdk,rfwb,oezh";
$images = explode(',', $image_names);
shuffle($images);
$new_width = "900";
$new_height= "300";
$split_size= "150";
echo "<ul id='sortable' style='width:" . $new_width . "px;height:" . $new_height . "px;'>";
foreach ($images as $key => $image_name) {
echo "<li class='ui-state-default' id='recordArr_$image_name' style='width:" . $split_size . "px;height:" . $split_size . "px;'>
<img src='images/$image_name.jpg' /></li>";
}
echo "</ul>";
?>
Code Explanation
You can see the puzzle on your screen and try to drag and drop images. You must be wondering why the puzzle is not working. That’s because we haven’t made the puzzle sortable yet. That’s where the magic happens. So lets make it sortable.

Include the following code snippet on the head section of your document after the js and css files.
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
opacity: 0.6,
cursor: 'move',
update: function() {
}
});
});
</script>
Now you can drag and drop the images and you will be able to see that images are changing in the puzzle. But there is no way you can check whether puzzle is solved or not unless its a very simple one. So now I am going to tell you how to check whether puzzle is solved using a very simple method.

Here is the code that will notify you when the puzzle is solved. Include it inside the update function of the code we created in the previous section
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
opacity: 0.6,
cursor: 'move',
update: function() {
var winningString = "oezh,rfwb,lsea,vkxl,ihrx,ilsc,eyen,mwgc,derv,logi,bwdk,scmz";
var currentString = '';
$('#sortable li').each(function(){
var imageId = $(this).attr("id");
currentString += imageId.replace("recordArr_", "")+",";
});
currentString = currentString.substr(0,(currentString.length) -1);
if(currentString == winningString){
alert("You Won");
}
}
});
});
</script>
Code Explanation
We have completed our tutorial on creating puzzles and now you can enjoy creating and solving puzzles.
Have you tried fixing the puzzle yet ?
You might have done it pretty easily since only 12 parts are available in the demo. But when the number of parts increases it will be very difficult unless you find out the correct method.
If you are a designer or developer who has knowledge in working with HTML DOM, you will be able to find the correct method. Drag and drop images a few times and see how the images are positioning. Then try to match that with how the HTML DOM works when you add and remove elements dynamically. I am sure that you will be able to figure it out.
So you can learn about the DOM while having fun with fixing puzzles. Let me know if you figure it out using the comments section.
Now we have completed creating a basic puzzle using jQuery drag and drop features. What we did was manually create image parts using some php code and including those parts of the puzzle. You can extend this by allowing users to upload images and create the image parts dynamically. Then allow the users to select the puzzle from a dropdown and fix it. So you will be able to create puzzles out of any image.
Sounds good right ? Here is some more functionality you can include in your puzzle.
1. Assign a time to fix the puzzle in a given time period using javascript setTimeout function.

2.Save image names in a database table with correct order and provide a score on how many parts have been completed inside the given time.

You can extend these features and create a puzzle site for users very easily. Let me know if you have any questions regarding using these puzzles or extending features. Use the instructions in the project files to execute the demo properly. Hope to hear from you.
Get The Only Freelancer crash course you will ever need to read!
Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and Sitepoint network. Make sure to contact him at www.innovativephp.com or follow him on Twitter
Wednesday, August 1st, 2012 06:36
Very nice puzzle idea! How would i set up so the puzzle has a timer til you complete it and then it allows you to post results on facebook?
Thursday, July 19th, 2012 16:26
Hello there it is really an amazing puzzle I need to redo it for children class as competition how can I make the swith the piece that you are holding, with the one in the place you drop, would you help me with this code. i need something very very easy for them. Thank you so much
Friday, June 29th, 2012 12:21
Its really cool.
The only thing that is annoying, is when you place a piece in the up row, it moves all the content.
Maybe you should swith the piece that you are holding, with the one in the place you drop to avoid this.
Thursday, June 21st, 2012 14:15
Very cool puzzle. It’s a new take on the jigsaw puzzle. As a webmaster, I would pay for a completed puzzle script like this.
Tuesday, June 12th, 2012 05:49
you did excellent work and useful for me as newbie in jquery tutorial.
Saturday, June 9th, 2012 08:01
Realy nice tutorial! But I find PHP part redundant. This could be done purely in JS/jQuery.
Wednesday, June 6th, 2012 10:01
Very cool tutorial, thanks. Shared it and gave a link to here.
Wednesday, June 6th, 2012 08:47
This is fantastic. I tried to complete the puzzle of 1WD, and I have won :)
If not, then it's time to learn how to:
You can trust 1stWebDesigner to help you become a better web designer!
- Jacob Cass | Just Creative
Just enter your name and email below and click Get Updates!
Rochester Oliveira
Tuesday, June 5th, 2012 13:57
Great tutorial!
Loved the idea since I saw the very first pitch of yours, but the final result is much better than I could imagine.
[]‘s
Rakhitha Nimesh
Wednesday, June 6th, 2012 00:40
Thanks Rochester for your comment.
Andrej Badin
Saturday, June 9th, 2012 08:01
Realy nice tutorial! But I find PHP part redundant. This could be done purely in JS/jQuery.
Jason Webb
Wednesday, June 6th, 2012 10:01
Very cool tutorial, thanks. Shared it and gave a link to here.
Dainis Graveris
Wednesday, June 6th, 2012 12:00
Jason, do you know it’s illegal to republish other blog content? You can use excerpt and featured image max, but not copy whole article on your own blog post. Please remove it or I will report that post.
If you didn’t know that, just letting you know, but it is the same as stealing.
Manuel Garcia
Wednesday, June 6th, 2012 08:47
This is fantastic. I tried to complete the puzzle of 1WD, and I have won :)
Dainis Graveris
Wednesday, June 6th, 2012 11:57
Hehe, congratulations Manuel! :) I feel like it still can be improved to avoid some little bugs, but awesome for some kind of marketing promotion!
Adina
Tuesday, June 12th, 2012 05:49
you did excellent work and useful for me as newbie in jquery tutorial.
Dainis Graveris
Tuesday, June 12th, 2012 07:48
Thanks! :) I hope you’ll find where to implement it :) Oh and one request, please use your real name in comments otherwise I won’t be able to accept your comment. Now I changed it to one of your team names since I couldn’t find any name in your site about me section.
John
Wednesday, August 1st, 2012 06:36
Very nice puzzle idea! How would i set up so the puzzle has a timer til you complete it and then it allows you to post results on facebook?
Pamela
Thursday, July 19th, 2012 16:26
Hello there it is really an amazing puzzle I need to redo it for children class as competition how can I make the swith the piece that you are holding, with the one in the place you drop, would you help me with this code. i need something very very easy for them. Thank you so much
Rakhitha Nimesh
Saturday, July 21st, 2012 02:40
Hi Pamela
I would love to make this puzzle for children. But I have to change everything inorder to make 2 images switch its places instead of current behavior. so it will take some time.
By the way what is the age group children that you planning this puzzle to be given ?
John
Thursday, August 2nd, 2012 22:43
Im interested in this as well could you email me on how to do it cheers
Annie
Thursday, June 21st, 2012 14:15
Very cool puzzle. It’s a new take on the jigsaw puzzle. As a webmaster, I would pay for a completed puzzle script like this.
Gabriel
Friday, June 29th, 2012 12:21
Its really cool.
The only thing that is annoying, is when you place a piece in the up row, it moves all the content.
Maybe you should swith the piece that you are holding, with the one in the place you drop to avoid this.
Rakhitha Nimesh
Monday, July 2nd, 2012 23:13
Thanks for the Comment
I agree with you about moving all the pieces when you move one. I did it purposely since otherwise it would be very easy. Now we have to find why its moving such a way, in order solve the puzzle. When you find the method it would be very easy. Think about HTML DOM.