www.webdeveloper.com
Results 1 to 5 of 5

Thread: Drag and drop

  1. #1
    Join Date
    Aug 2012
    Location
    North Carolina
    Posts
    3

    Drag and drop

    Hi, Iím working on a web page which displays the game of chess. Iíve managed to make the board, also put the pieces where there supposed to be, but Iíve been having a hard time making the chess pieces move from one place to another. I need some advice if there any tags or functions etcÖ. that I can use so I can drag my pieces and put them in an empty spot. And also allow me to put a piece on another piece then the piece disappears leaving the other piece.

    THE CODE SO FAR:

    <html>

    <head>
    <title>Chess Board using PHP</title>

    <style type="text/css">
    td
    {
    height:75px; width:75px;
    }

    table
    {
    border: 4px solid black;
    border-collapse:collapse;
    }

    h2
    {
    font-family:Arial; font-size:25px;
    color:royalblue; font-weight: bold;
    text-align: center;
    }

    </style>

    <script>
    function dragIt(target, e) {
    e.dataTransfer.setData('SpanImg', target.id);
    }
    function dropIt(target, e) {
    var id = e.dataTransfer.getData('SpanImg');
    target.appendChild(document.getElementById(id));
    e.preventDefault();
    }
    function tra****(target, e) {
    var id = e.dataTransfer.getData('SpanImg');
    removeElement(id);
    e.preventDefault();
    }
    function removeElement(id) {
    var d_node = document.getElementById(id);
    d_node.parentNode.removeChild(d_node);
    }
    </script>


    </head>

    <body style="background-color: red;">

    <h2>Chess Game</h2>
    <!--A chessboard is the type of checkerboard used in the board game chess,
    and consists of 64 squares (eight rows and eight columns) arranged in two alternating
    colors black and white-->

    <?php
    echo "<table border=\"1\" align=\"center\">";

    //During 1 iteration 2 top rows are created.
    //For loop will iterate 4 times creating 8 rows.



    $board = array(
    array('♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'),
    array('♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'),
    array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
    array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
    array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
    array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
    array('♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'),
    array('♜', '♞', '♝', '♚', '♛', '♝', '♞', '♜'));








    for($i=4;$i>=1;$i--)
    {

    echo "<tr align=\"center\">";
    //For loop creates 1st row starting from black
    for($j=0;$j<8;$j++)
    {
    if(($j%2)==0)
    {
    $color = "blue";
    }
    else
    {
    $color = "white";

    }
    switch ($i)
    {
    case 4:
    $s=0;
    break;
    case 3:
    $s=2;
    break;
    case 2:
    $s=4;
    break;
    case 1:
    $s=6;
    break;
    }
    $henry = $board[$s][$j];

    echo <<<_END
    <html>
    <head>
    <script>

    </script>
    <body>
    <td bgcolor ="$color" id="holder" ondrop="dropIt(this, event)" ondragenter="return false" ondragover="return false">
    <font size=26> <span draggable="true" id="lt" ondragstart="dragIt(this, event)">$henry</span></td>
    </body>
    </html>
    _END;



    }//for loop ends
    echo "</tr>";

    //Second Row starting with white
    echo "<tr align=\"center\">";

    $s+= 1;
    //For loop creates 2nd row starting from white
    for($j=7;$j>=0;$j--)
    {
    if(($j%2)==0)
    {
    $color = "blue";
    }
    else
    {
    $color = "white";
    }

    switch ($i)
    {
    case 4:
    $s=1;
    break;
    case 3:
    $s=3;
    break;
    case 2:
    $s=5;
    break;
    case 1:
    $s=7;
    break;
    }



    $charles = $board[$s][7-$j];

    echo <<<_END
    <html>
    <head>
    <script type="text/javascript">
    function allowDrop(ev)
    {
    ev.preventDefault();
    }

    function drag(ev)
    {
    ev.dataTransfer.setData("Text",ev.target.id);
    }

    function drop(ev)
    {
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
    }
    </script>

    </head>
    <body>



    <td bgcolor ="$color" id="hat" ondrop="dropIt(this, event)" ondragenter="return false" ondragover="return false">
    <font size=26> <span draggable="true" id="lp" ondragstart="dragIt(this, event)">$charles</span></td>






    </body>
    </html>
    _END;

    }//for loop ends
    echo "</tr>";


    }//outer for ends.
    echo "</table>";

    ?>

    </body>
    </html>

  2. #2
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    Okay, I'm not going to even attempt at writing a chess game in JavaScript (which is essentially what you're asking for), but I will help you out with your "drag 'n drop" code.

    I thought this would make a neat little tutorial, so thanks for giving me a little project to work on this afternoon. I've written some code which allows a <div> element to be dragged and dropped in any place in the browser.

    Like I said, I'm not interested in writing your chess game for you because that would take too long and I don't think you're going to get anyone here to do this for you. The code I've written here isn't too generic, i.e., it doesn't work with any element. However, with a little modification, this would be easy to achieve.

    Here's the code in its entirety (copy & paste job, it's a complete example). I've tested this in the latest versions of the top 5 browsers and it worked in each of them. I haven't tested it in older versions of said browsers:

    For the record, I've actually written a checkers/draughts game before in C++ and I think you'd be better off placing all your "pieces" in a single array of 64.
    Code:
    <!DOCTYPE html>
    
    <style type="text/css">
    
    #drag_me
    {
    	position: absolute;
    	
    	background-color: #0CF;
    	
    	top: 50px;
    	left: 50px;
    
    	border: 1px solid #000;
    	padding: 30px 20px 30px 20px;
    	
    	font-size: 20pt;
    	font-weight: bold;
    	color: #F00;
    }
    
    .bg1
    {	
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #000;
    
    	border: 1px solid #000;
    }
    
    .bg2
    {
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #fff;
    	
    	border: 1px solid #000;
    }
    
    </style>
    
    Mouse X: 	  <input type="text" size="10" id="coords_x" />
    Mouse Y: 	  <input type="text" size="10" id="coords_y" />
    Mouse Status: <input type="text" size="10" id="mouse_status" value="Up" />
    
    <!-- The draggable element -->
    <div id="drag_me">Drag Me</div>
    
    <div style="margin-bottom: 50px;"><!-- Space --></div>
    
    <!-- Checkered background for perspective -->
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    
    
    <script type="text/javascript">
    
    // The offsets for the original element.
    var offset_x = 0;
    var offset_y = 0;
    
    // Mouse coordinates.
    var mouse_x = 0;
    var mouse_y = 0;
    
    // Original z-index.
    var z_index = 0;
    
    // Add a "mousemove" event listener to the window and update
    // the <input> elements with mouse position.
    window.addEventListener
    (
    	"mousemove", 
    	function nothing()
    	{
    		document.getElementById("coords_x").value = window.event.clientX;
    		document.getElementById("coords_y").value = window.event.clientY;	
    	}, false
    );
    
    // Event listeners for the "drag_me" element.
    document.getElementById("drag_me").addEventListener("mousedown", start_drag, false);
    document.getElementById("drag_me").addEventListener("mouseup",     end_drag, false);
    
    // Firefox requires the event be passed in as a parameter.
    // Other browsers don't care.
    function start_drag(event)
    {
    	// Once inside this function (once mousedown has fired for the element)
    	// we can create an anonymous function to handle
    	// the dragging. Firefox requires event to be passed in as a parameter.
    	document.onmousedown = function(event)
    	{
    		// event.target (standards compliant), srcElement (MSIE).
    		if((event.target || event.srcElement).id == "drag_me")
    		{
    			document.body.style.cursor = "move";
    			document.getElementById("mouse_status").value = "Down";
    			
    			// Apply some effects (change opacity and border).
    			drag_effects(document.getElementById("drag_me"));
    			
    			// Save mouse position.
    			mouse_x = event.clientX;
    			mouse_y = event.clientY;
    			
    			// Save offset of element.
    			offset_x = document.getElementById("drag_me").offsetLeft;
    			offset_y = document.getElementById("drag_me").offsetTop;
    			
    			// Retain z-index for after dragging is done.
    			z_index = document.getElementById("drag_me").style.zIndex;
    			
    			// Temporarily make element upmost object.
    			document.getElementById("drag_me").style.zIndex = 99999;
    			
    			// The "dragging" part is created with an anonymous function.
    			document.onmousemove = function(event)
    			{
    				document.getElementById("drag_me").style.left = (event.clientX + offset_x) - mouse_x + "px";
    				document.getElementById("drag_me").style.top  = (event.clientY + offset_y) - mouse_y + "px";		
    			}
    			
    			// Disable text selection to page doesn't get highlighted with dragging.
    			document.onselectstart = function () {return false;};
    			event.target.ondragstart = function() {return false;};		
    			return false;
    		}
    	}
    }
    
    function end_drag()
    {
    	var element = document.getElementById("drag_me");
    	
    	element.style.zIndex = z_index;
    	element.style.border = "1px solid #000";
    	element.style.opacity = 1.0;
    	
    	document.body.style.cursor = "auto";
    	document.getElementById("mouse_status").value = "Up";
    	
    	document.onmousemove = null;
    	document.onmousedown = null;
    }
    
    function drag_effects(element)
    {
    	element.style.border = "2px solid #F00";
    	element.style.opacity = 0.5;
    }
    </script>
    Last edited by George88; 08-18-2012 at 03:52 PM.

  3. #3
    Join Date
    Aug 2012
    Location
    North Carolina
    Posts
    3

    Thanks

    I've tryed to run you code, and i couldnt get any thing on a webpage. Your right I should have not asked help for a chess game. I should have just been specific and say I need help with drag and drop. Do you know any tutorials for drag and drop on the internet or any examples that I can see. I'll study your code more for some hints.

  4. #4
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    Not sure why the code doesn't work for you. It should at least display the HTML and CSS. How did you try running it?

    See http://jsfiddle.net/yv7Zh/

    Edit: just a side note, but I saw some debug errors in Firebug due to the fact that the event wasn't being passed in to the anonymous function which sets the X and Y coordinates in the input fields. I've updated:

    Code:
    <!DOCTYPE html>
    
    <style type="text/css">
    
    #drag_me, #drag_me2
    {
    	position: absolute;
    	
    	background-color: #0CF;
    	
    	top: 50px;
    	left: 50px;
    
    	border: 1px solid #000;
    	padding: 30px 20px 30px 20px;
    	
    	font-size: 20pt;
    	font-weight: bold;
    	color: #F00;
    }
    
    .bg1
    {	
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #000;
    
    	border: 1px solid #000;
    }
    
    .bg2
    {
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #fff;
    	
    	border: 1px solid #000;
    }
    
    </style>
    
    Mouse X: 	  <input type="text" size="10" id="coords_x" />
    Mouse Y: 	  <input type="text" size="10" id="coords_y" />
    Mouse Status: <input type="text" size="10" id="mouse_status" value="Up" />
    
    <!-- The draggable element -->
    <div id="drag_me">Drag Me</div>
    
    <div style="margin-bottom: 50px;"><!-- Space --></div>
    
    <!-- Checkered background for perspective -->
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    
    
    <script type="text/javascript">
    
    // The offsets for the original element.
    var offset_x = 0;
    var offset_y = 0;
    
    // Mouse coordinates.
    var mouse_x = 0;
    var mouse_y = 0;
    
    // Original z-index.
    var z_index = 0;
    
    // Add a "mousemove" event listener to the window and update
    // the <input> elements with mouse position.
    window.addEventListener
    (
    	"mousemove", 
    	function(event)
    	{
    		e = event;
    		document.getElementById("coords_x").value = e.clientX;
    		document.getElementById("coords_y").value = e.clientY;	
    	}, false
    );
    
    // Event listeners for the "drag_me" element.
    document.getElementById("drag_me").addEventListener("mousedown", start_drag, false);
    document.getElementById("drag_me").addEventListener("mouseup",     end_drag, false);
    
    // Firefox requires the event be passed in as a parameter.
    // Other browsers don't care.
    function start_drag(event)
    {
    	// Once inside this function (once mousedown has fired for the element)
    	// we can create an anonymous function to handle
    	// the dragging. Firefox requires event to be passed in as a parameter.
    	document.onmousedown = function(event)
    	{
    		// event.target (standards compliant), srcElement (MSIE).
    		if((event.target || event.srcElement).id == "drag_me")
    		{
    			document.body.style.cursor = "move";
    			document.getElementById("mouse_status").value = "Down";
    			
    			// Apply some effects (change opacity and border).
    			drag_effects(document.getElementById("drag_me"));
    			
    			// Save mouse position.
    			mouse_x = event.clientX;
    			mouse_y = event.clientY;
    			
    			// Save offset of element.
    			offset_x = document.getElementById("drag_me").offsetLeft;
    			offset_y = document.getElementById("drag_me").offsetTop;
    			
    			// Retain z-index for after dragging is done.
    			z_index = document.getElementById("drag_me").style.zIndex;
    			
    			// Temporarily make element upmost object.
    			document.getElementById("drag_me").style.zIndex = 99999;
    			
    			// The "dragging" part is created with an anonymous function.
    			document.onmousemove = function(event)
    			{
    				document.getElementById("drag_me").style.left = (event.clientX + offset_x) - mouse_x + "px";
    				document.getElementById("drag_me").style.top  = (event.clientY + offset_y) - mouse_y + "px";		
    			}
    			
    			// Disable text selection to page doesn't get highlighted with dragging.
    			document.onselectstart = function () {return false;}
    			event.target.ondragstart = function() {return false;}
    			return false;
    		}
    	}
    }
    
    function end_drag()
    {
    	var element = document.getElementById("drag_me");
    	
    	element.style.zIndex = z_index;
    	element.style.border = "1px solid #000";
    	element.style.opacity = 1.0;
    	
    	document.body.style.cursor = "auto";
    	document.getElementById("mouse_status").value = "Up";
    	
    	document.onmousemove = null;
    	document.onmousedown = null;
    }
    
    function drag_effects(element)
    {
    	element.style.border = "2px solid #F00";
    	element.style.opacity = 0.5;
    }
    </script>
    Last edited by George88; 08-20-2012 at 08:05 AM.

  5. #5
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    Sorry to make another post here, but out of my own interest I've made this code generic. It now works with any element that has a given class name. Thought I may as well share it here plus I'm going to write a tutorial for my site's resource on JavaScript drag and drop.

    Thanks for the inspiration francis_semazzi. Also, I must apologise for the messy in-line styling and somewhat ugly source. If anyone is actually going to use this code, I recommend separating style, script and markup. Since this is a working example (copy & paste code), it was necessary.

    Take note that I am using document.getElementsByClassName, which is not supported by any MSIE less than version 9. See full details of browser support here http://caniuse.com/getelementsbyclassname

    You should find that this code is almost 100&#37; bug free and works in each of the top 5 browsers (latest versions).

    See it working on JsFiddle: http://jsfiddle.net/WR9n5/
    Code:
    <!DOCTYPE html>
    
    <style type="text/css">
    
    .draggable
    {
    	position: absolute;
    	
    	background-color: #0CF;
    	
    	top: 50px;
    	left: 50px;
    
    	border: 1px solid #000;
    	padding: 30px 20px 30px 20px;
    	
    	font-size: 20pt;
    	font-weight: bold;
    	color: #F00;
    }
    
    .bg1
    {	
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #000;
    
    	border: 1px solid #000;
    }
    
    .bg2
    {
    	width: 100px;
    	height: 100px;
    	display: table-cell;
    	background-color: #fff;
    	
    	border: 1px solid #000;
    }
    
    </style>
    
    Mouse X: 	  <input type="text" size="10" id="coords_x" />
    Mouse Y: 	  <input type="text" size="10" id="coords_y" />
    Mouse Status: <input type="text" size="10" id="mouse_status" value="Up" />
    
    <!-- The draggable element -->
    <div class="draggable">Drag Me</div>
    <div class="draggable" style="top: 150px;">Drag It</div>
    <div class="draggable" style="top: 250px;">Try Me</div>
    <div class="draggable" style="top: 350px;">Try Me</div>
    
    <div style="margin-bottom: 50px;"><!-- Space --></div>
    
    <!-- Checkered background for perspective -->
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    <div class="bg1"></div>
    <div class="bg2"></div>
    
    
    <script type="text/javascript">
    
    // The offsets for the original element.
    var offset_x = 0;
    var offset_y = 0;
    
    // Mouse coordinates.
    var mouse_x = 0;
    var mouse_y = 0;
    
    // Original z-index.
    var z_index = 0;
    
    window.addEventListener
    (
    	"mousemove", 
    	function(event)
    	{
    		e = event;
    		document.getElementById("coords_x").value = e.clientX;
    		document.getElementById("coords_y").value = e.clientY;	
    	}, false
    );
    
    var get_elements = new Array();
    
    get_elements = document.getElementsByClassName("draggable");
    
    for(var i = 0; i < get_elements.length; i++)
    {
    	if(get_elements[i].id == "")
    		get_elements[i].id = Math.random(99999);
    		
    	document.getElementById(get_elements[i].id).addEventListener("mousedown", start_drag, false);
    	document.getElementById(get_elements[i].id).addEventListener("mouseup",     end_drag, false);
    }
    
    function start_drag(event)
    {
    	e = event;
    	
    	if(e.button != 0)
    		return false;
    		
    	document.onmousedown = function(event)
    	{
    		if((e.target || e.srcElement).className == "draggable")
    		{
    			// Get the currently selected element.
    			var current_element = e.target.id;
    			
    			document.body.style.cursor = "move";
    			document.getElementById("mouse_status").value = "Down";
    			
    			drag_effects(document.getElementById((e.target || e.srcElement).id));
    			
    			mouse_x = event.clientX;
    			mouse_y = event.clientY;
    			
    			offset_x = document.getElementById((e.target || e.srcElement).id).offsetLeft;
    			offset_y = document.getElementById((e.target || e.srcElement).id).offsetTop;
    			
    			z_index = document.getElementById((e.target || e.srcElement).id).style.zIndex;
    			
    			document.getElementById((e.target || e.srcElement).id).style.zIndex = 99999;
    			
    			document.onmousemove = function(event)
    			{
    				document.getElementById(current_element).style.left = (e.clientX + offset_x) - mouse_x + "px";
    				document.getElementById(current_element).style.top  = (e.clientY + offset_y) - mouse_y + "px";		
    			}
    			
    			document.onselectstart = function () {return false;}
    			event.target.ondragstart = function() {return false;}
    			return false;
    		}
    	}
    }
    
    function end_drag()
    {
    	var element = document.getElementById((e.target || e.srcElement).id);
    	
    	element.style.zIndex = z_index;
    	element.style.border = "1px solid #000";
    	element.style.opacity = 1.0;
    	
    	document.body.style.cursor = "auto";
    	document.getElementById("mouse_status").value = "Up";
    	
    	document.onmousemove = null;
    	document.onmousedown = null;
    }
    
    function drag_effects(element)
    {
    	element.style.border = "2px solid #F00";
    	element.style.opacity = 0.5;
    }
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles