I am attempting to code a puzzle using HTML, CSS, and JavaScript. Currently my code accepts an image and then sets that image to the background of a div element. The JavaScript then appends 16 child div elements into the html file. I want my code to move each image segment from the parent element to its respective child.
I have a div element in my HTML:
<div id="image"></div>
The JavaScript code appends 16 child div elements each with a unique id:
$(document).ready(function(){
let $url;
$('#gameImage').keypress(function(e){
if(e.keyCode == 13){
$url = $('#gameImage').val();
console.log($url);
$('#gameImage').val('');
$('#image').css("background-image", `url(${$url})`);
for(let i=0;i<16;i++){
console.log(i);
$('#image').append('<div class="piece" id= "segment'+i+'"></div>')
}
}
});
})
I want to be able to click on these child elements and scramble around the pieces of the puzzle however the image is a background image for the parent element.
I have tried following some of the suggestions from this post Cutting an Image into pieces through Javascript however I cannot move the images if set background-position for each piece. Other solutions mentioned using canvas but I am not able to use canvas to make a movable div element.