JavaScript - Simple Html5 Drag/drop Javascript Question
I need to be able to drag an image from one browser window to a form text input in a different window, populating it with the image file name.
I can do this easily, except that the result is the whole url, and I only want the filename to be inserted. In other words, it inserts http://www.path/path/file.jpg, but I just want to end up with file.jpg. I believe the file object .name property holds the info I need, but I don't know how to populate the input field with it. Any help appreciated. Similar TutorialsI am having a problem sending info to a database. I have set up drag and drop with HTML5 and it is working, but I need to be able to get the values of the images uploaded to the database when each one is dropped into a dropzone. I don't need to upload the images to the database - just need the value of each image sent to it. Here is the HTML: Code: <ul id="images"> <li><a id="1" draggable="true"><img src="images/1.jpg" value = "flower"></a></li> <li><a id="2" draggable="true"><img src="images/2.jpg" value = "boy"></a></li> <li><a id="3" draggable="true"><img src="images/3.jpg" value = "girl"></a></li> </ul> <form name = "objects" id="form" action = "form.php" method = "post"> <div class="drop_zones"> <div class="drop_zone" id="drop_zone1" droppable="true" type = "text" name = "drop_zone1"> </div> <div class="drop_zone" id="drop_zone2" droppable="true" type = "text" name = "drop_zone2"> </div> <div class="drop_zone" id="drop_zone3" droppable="true" type = "text" type = "file" name = "drop_zone3"> </div> </div> and the javascript Code: var addEvent = (function () { if (document.addEventListener) { return function (el, type, fn) { if (el && el.nodeName || el === window) { el.addEventListener(type, fn, false); } else if (el && el.length) { for (var i = 0; i < el.length; i++) { addEvent(el[i], type, fn); } } }; } else { return function (el, type, fn) { if (el && el.nodeName || el === window) { el.attachEvent('on' + type, function () { return fn.call(el, window.event); }); } else if (el && el.length) { for (var i = 0; i < el.length; i++) { addEvent(el[i], type, fn); } } }; } })(); var dragItems; updateDataTransfer(); var dropAreas = document.querySelectorAll('[droppable=true]'); function cancel(e) { if (e.preventDefault) { e.preventDefault(); } return false; } function updateDataTransfer() { dragItems = document.querySelectorAll('[draggable=true]'); for (var i = 0; i < dragItems.length; i++) { addEvent(dragItems[i], 'dragstart', function (event) { event.dataTransfer.setData('obj_id', this.id); return false; }); } } addEvent(dropAreas, 'dragover', function (event) { if (event.preventDefault) event.preventDefault(); this.style.borderColor = "#000"; return false; }); addEvent(dropAreas, 'dragleave', function (event) { if (event.preventDefault) event.preventDefault(); this.style.borderColor = "#ccc"; return false; }); addEvent(dropAreas, 'dragenter', cancel); // drop event handler addEvent(dropAreas, 'drop', function (event) { if (event.preventDefault) event.preventDefault(); // get dropped object var iObj = event.dataTransfer.getData('obj_id'); var oldObj = document.getElementById(iObj); // get its image src var oldSrc = oldObj.childNodes[0].src; oldObj.className += 'hidden'; var oldThis = this; setTimeout(function() { oldObj.parentNode.removeChild(oldObj); // remove object from DOM // add similar object in another place oldThis.innerHTML += '<a id="'+iObj+'" draggable="true"><img src="'+oldSrc+'" /> </a>'; // and update event handlers updateDataTransfer(); // little customization oldThis.style.borderColor = "#ccc"; }, 500); return false; }); and the php PHP Code: <?php $sql="INSERT INTO table_answers (drop_zone1, drop_zone2, drop_zone3) VALUES ('$_POST[drop_zone1]','$_POST[drop_zone2]','$_POST[drop_zone3]')"; if (!mysql_query($sql,$db)) { die('Error: ' . mysql_error()); } echo $_POST["drop_zone1"]; echo $_POST["drop_zone2"]; echo $_POST["drop_zone3"]; ?> There is no error, it is not registering that there is something in the dropzone - nothing is being sent through the php. I have tried doing it with just text(instead of the image) and that won't work either. I am unsure of how to target the value of each image through javascript/php. Please help if you can, Thanks Hi, I am currently working in mail client project. The mails are displayed in the html table. I have an requirement to drag and drop the mails from the Inbox to another folder. Can you please suggest how to proceed with this. Thanks in advance. Regards, Anne. Hi, I have the following code for drag and drop objects in any page. My target: I want to be able to drag and drop the advertisement images that come on top of the page. It works most of the time, but sometime page crashes. I use google chrome as a bookmarklet. Code: Code: javascript:var d=document,b=d.body,i="innerHTML",s="style",p="position",a="absolute",r="relative",w1="offsetWidth",w2="width",h1="offsetHeight",h2="height",t1="offsetTop",t2="top",l1="offsetLeft",l2="left",drag=false;function down(e){drag=true;z=event.srcElement;z[s][p]=r;x=event.clientX;y=event.clientY;zx=z[l1];zy=z[t1];d.onmousemove=move}function up(e){drag=false;}function move(e){if(drag){z[s][l2]=zx+event.clientX-x;z[s][t2]=zy+event.clientY-y}}document.onmousedown=down;document.onmouseup=up; Any improvements in the code is appreciated. Does anybody have a advanced better code, because I am just medium in javascript. Hi, I'm doing a project for college where i have create a game in which images must be dragged-and-dropped into a certain order. The game should: * Be web-based, using client-side JavaScript * Include At LEAST FIVE moveable images * Randomise the positions of the images at start-up * Check the positions of the images and notify the user when they are in the correct order * Record and display the time taken to sort the images All of these requirements are working, i have div tags set up with borders around them, so that the user knows where to place the images. The thing i would like to do is when an image is dragged say within 20px of a div that the image snaps to the div...can anybody suggest a way to do this or perhaps a code suggestion. Code: <html> <head> <script language="javascript" type="text/javascript"> // cursor drag and drop variables var IE = document.all; var selectedImage = null; var tx = 0; var ty= 0; var x = 0; var y = 0; //change names var rand=null; var myround=null; //timer variables var c= 0; var t; var timer_is_on= null // Where images are supposed to go var image1 = new Array ("804px","70px"); var image2 = new Array ("661px","70px"); var image3 = new Array ("225px","70px"); var image4 = new Array ("950px","70px"); var image5 = new Array ("517px","70px"); var image6 = new Array ("372px","70px"); var picLocs = new Array(image1,image2,image3,image4,image5,image6); // var correctPitchPosition = new Array("0","0","0","0","0","0"); var allCorrect = true; var correctPosition = 50; var counter = 0; // start drag and drop function enableDragging(evt) { if(IE) { selectedImage = event.srcElement; } else { selectedImage = evt.target; } tx = parseInt (selectedImage.style.left +0) ty = parseInt (selectedImage.style.top +0) if(IE) { x = event.clientX; y = event.clientY; } else { x = evt.clientX; y = evt.clientY; } document.onmousemove = dragImage; document.onmouseup = disableDragging; return false; } // Do drag and Drop function dragImage(evt) { if (!evt) evt = window.event; selectedImage.style.left = tx + evt.clientX -x; selectedImage.style.top = ty + evt.clientY- y; return false; } //Stop Drag and Drop function disableDragging() { correctImg(); document.onmousemove = null; document.onmouseup = null; correctTeam(); return false; } //Set Up Events for every image function setupEvents() { for (var j=0; j < document.images.length; j++) { document.images[j].onmousedown = enableDragging; } } //Timer Control function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } //Timer function function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } //Stop Timer function stopCount() { clearTimeout(t); timer_is_on=0; alert("Timer stopped!"); } function gameStart() { doTimer(); setupEvents(); c = 0; for (var i=0; i < 6; i++) { randX = Math.random()*800; myroundX = Math.floor(randX); document.images[i].style.left = myroundX; } alert("You must put the Liverpool player in their correct spaces based on the descriptions, press OK to continue") } function correctImg() { for (i=0; i < picLocs.length; i++) { if ( parseInt(document.images[i].style.left) > parseInt(picLocs [i][0])-correctPosition && parseInt(document.images[i].style.left) < parseInt(picLocs[i][0])+correctPosition && parseInt(document.images[i].style.top) > parseInt(picLocs[i][1])-correctPosition && parseInt(document.images[i].style.top) < parseInt(picLocs[i][1])+correctPosition) { correctPitchPosition[i] = 1; } } } function correctTeam() { for(var k=0; k < 6; k++) { if(correctPitchPosition[k] == 1) counter = counter + 1; } if (counter==6) { alert("Your time was " + c + " well done!"); stopCount(); } counter=0; } </script> <link href="_css/styles.css" rel="stylesheet" type="text/css"> </head> <body> <img src="_images/agger.jpg" alt="Daniel Agger" class="imgPos" style="position: absolute; top: 320px; left: 804px" /> <img src="_images/carragher.jpg" alt="Jamie Carragher" class="imgPos" style="position: absolute; top: 320px; left: 950px"/> <img src="_images/gerrard.jpg" alt="Steven Gerrard" class="imgPos" style="position: absolute; top: 320px; left: 372px"/> <img src="_images/mascherano.jpg" alt="Javier Mascherano" class="imgPos" style="position: absolute; top: 320px; left: 225px"/> <img src="_images/reina.jpg" alt="Pepe Reina" class="imgPos" style="position: absolute; top: 320px; left: 517px"/> <img src="_images/torres.jpg" alt="Fernando Torres" class="imgPos" style="position: absolute; top: 320px; left: 661px"/> <div id="desAgger" class="description" style="left:804px;"> <p>"I have a wicked left foot but i like to stay and defend"</p> </div> <div id="desMascherano" class="description" style="left:950px;"> <p>"I'm a tenacious Argentinian who'll chase anything down"</p> </div> <div id="desTorres" class="description" style="left:372px;"> <p>"I am from Spain, they call me El Nino"</p> </div> <div id="desGerrard" class="description" style="left:225px;"> <p>"I'm the captain of Liverpool FC, and a proud scouser"</p> </div> <div id="desReina" class="description" style="left:517px;"> <p>"My real name is Jose and i'm the Liverpool goalkeeper"</p> </div> <div id="desCarragher" class="description" style="left:661px;"> <p>"I'm the defensive stalwart, and vice-captain"</p> </div> <form> <input type="button" value="Start game!" onClick="gameStart()" style="position:absolute; left: 500px; top: 539px; width: 20px; height: 20px; width: 120px; height: 40px;"> <input type="button" value="Stop count!" onClick="stopCount()" style="position: absolute; left: 792px; top: 537px; width: 120px; height: 40px;"> <input type="text" disabled id="txt" style="position: absolute; top: 547px; left: 633px" value="0" readonly="readonly"> </form> </body> </html> Thanks very much in advance I have done drag and drop of popup in JavaScript and it is dragged in all directions properly but down.MouseUp event is not triggered properly when I drag the popup towards down.So that it is moving even though I released mouse. I am really screwed up with this bug.Please help..I have to resolve it urgently.... Here is my code.. Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <style> body{ margin:0px; padding:0px; } iframe{ width:800px; height:500px; } img{border:none;} .parentDisabled { width:100%; height:100% background-color:red; position:absolute; top:0; left:0; display:block; border:1px solid blue; } #popup{ position:absolute; width:800px; height:500px; border:2px solid #999188; display:none; } #header{ padding-right:0px; width:800px; } #close{ cursor:hand; width:15px; position: absolute; right:0; top:0; padding:2px 2px 0px 0px; } #move{ cursor:move; background:#999188; width:800px; line-height:10px; } #container{ } .navigate{ border:1px solid black ; background:#CC00FF; color:white; padding:5px; cursor:hand; font-weight:bold; width:150px; } </style> </HEAD> <BODY> <div onClick="showPopUp('w3schools');" class="navigate">W3Schools</div> <div onClick="showPopUp('yahoo');" class="navigate">Yahoo</div> <div onClick="showPopUp('linkedin');" class="navigate">LinkedIn</div> <div onClick="showPopUp('vistex');" class="navigate">Vistex</div> <div id="popup"> <div id="header"> <span id="move"></span> <span id="close"><img src="close_red.gif" onClick="closePopUp()" alt="Close"/></span> </div> <div id="container"> <iframe name="frame" id="Page_View" frameborder=0> page cannot be displayed </iframe> </div> </div> </BODY> <script> var popUpEle=null; function showPopUp(value,evt) { evt = evt ? evt : window.event; var left=evt.clientX; var top=evt.clientY; popUpEle = document.getElementById('popup'); if(popUpEle) { closePopUp(); var url= "http://www."+value+".com"; document.getElementById('Page_View').src=url; popUpEle.style.left=left; popUpEle.style.top=top; popUpEle.style.filter="revealTrans( transition=1, duration=1)"; popUpEle.filters.revealTrans( transition=1, duration=1).Apply(); popUpEle.filters.revealTrans( transition=1, duration=1).Play(); popUpEle.style.display="inline"; } } function closePopUp(){ if(popUpEle) { popUpEle.style.filter="revealTrans( transition=0, duration=4)"; popUpEle.filters.revealTrans( transition=0, duration=5).Apply(); popUpEle.filters.revealTrans( transition=0, duration=5).Play(); popUpEle.style.display="none"; } } var dragApproved=false; var DragHandler = { // private property. _oElem : null, // public method. Attach drag handler to an element. attach : function(oElem) { oElem.onmousedown = DragHandler._dragBegin; // callbacks oElem.dragBegin = new Function(); oElem.drag = new Function(); oElem.dragEnd = new Function(); return oElem; }, // private method. Begin drag process. _dragBegin : function(e) { var oElem = DragHandler._oElem = this; if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; } if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; } var x = parseInt(oElem.style.left); var y = parseInt(oElem.style.top); e = e ? e : window.event; if (e.pageX || e.pageY) { oElem.mouseX = e.pageX; oElem.mouseY = e.pageY; } else if (e.clientX || e.clientY) { oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft; oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop; } document.onmousemove = DragHandler._drag; document.onmouseup = DragHandler._dragEnd; return false; }, // private method. Drag (move) element. _drag : function(e) { var oElem = DragHandler._oElem; var x = parseInt(oElem.style.left); var y = parseInt(oElem.style.top); e = e ? e : window.event; var clientXTmp,clientYTmp; if (e.pageX || e.pageY) { clientXTmp = e.pageX; clientXTmp = e.pageY; } else if (e.clientX || e.clientY) { clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft; clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop; } var tmpX = x + (clientXTmp - oElem.mouseX); var tmpY = y + (clientYTmp - oElem.mouseY); if(tmpX<=0){tmpX = 0;} if(tmpY<=0){tmpY = 0;} oElem.style.left = tmpX + 'px'; oElem.style.top = tmpY + 'px'; oElem.mouseX = clientXTmp; oElem.mouseY = clientYTmp; return false; }, // private method. Stop drag process. _dragEnd : function() { var oElem = DragHandler._oElem; document.onmousemove = null; document.onmouseup = null; DragHandler._oElem = null; } } DragHandler.attach(document.getElementById('popup'));</script> </HTML> There are 2 images, and 2 locations, lets named it img1, img2, loc1, and loc2. What im trying to do is drag and drop img1 to loc1, which mean i don't want img1 to be drop in loc2, i want the specific image drop on specific location. Code: function dropIn(evt) { var root = document.getElementsByTagName("body")[0]; evt.preventDefault(); var id = evt.dataTransfer.getData("text"); if(ev.target.getAttribute('data-drop') == id) ev.target.appendChild(document.getElementById(id)); } <div id="box1" style="position: absolute; top: 220px; left: 220px;" ondragover="dragIn();" ondrop="dropIn();" > <img id="img1" class="resize" src="wreck.jpg" ondragstart="dragBegin()" draggable="true" style="cursor:move;"/></div> <div id="loc1" data-drop="img1" style="border:1px solid black; position:absolute; left:400px; top:150px; width:160px; height:200px;"ondragover="dragIn();" ondrop="dropIn();" ></div> <div id="box2" style="position: absolute; top: 220px; left: 300px;" ondragover="dragIn();" ondrop="dropIn();" > <img id="img2" class="resize" src="nah.jpg" ondragstart="dragBegin()" draggable="true" style="cursor:move;"/></div> <div id="loc2" data-drop="img2" style="border:1px solid black; position:absolute; left:560px; top:150px; width:160px; height:200px;"ondragover="dragIn();" ondrop="dropIn();" ></div> so far the code above allow me to achieve what i want, but its not perfect, when i drop img1 to loc2, it did nothing. What i really want is when i drop img1 to loc2, the img1 is still dropped on the loc1. No matter where the img1 will be drop by user, the result of img1 will still be dropped on loc1, and same goes to img2, it will always be dropped on the loc2. I tried this but its not working Code: if(evt.target.getAttribute('data-drop') == id){ evt.target.appendChild(document.getElementById(id)); } else{ evt.target.appendChild(document.getElementsByAttribute('data-drop')); } is there any soloution for me? Thanks alot Hi, I have a scenario in which i have to drag and drop some objects in a circular motion, but under spacific boundaries. To expain the scenario better, I have attached a image of the problem. If possible kindly provide me code, either logical description/solution of the problem would be very helpful. Thanks Sa9chit I have made a code which is for a 9 tile picture puzzle.And i have done it for click event.now i want to make it possible to drag and drop to swap divs rather than clicking.So how do i swap divs with only javascript.[p.s my divs are dynamically created]
After months of searching the web, and found nothing about javascript drag and drop kinetic scrolling, I decided to develop it by myself, relying on my flash knowledge, because I was created kinetic scrolling in flash with ease! And now, after learning javascript a little bit and spending almost a week, I finally succeded to create such a thing in javascript! And I'm ready to share it with you, but I need a little help from someone more experienced to fix an small issue ! Here is the code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JavaScript Drag and Drop Tutorial</title> </head> <body onload="borders()"> <div style="position:absolute; left:0%; top:0%; "> <style type="text/css"> .drag { position: absolute; } </style> <div style=" position:absolute; width:100%; height = 100%; left:0%; top: 0%" id="pageContainer"> <input id="1" class="drag" style="width:100px; height:100px; top: 0px" type="submit" value="Drag 'n' throw me"> <input id="2" class="drag" style="width:100px; height:100px; top: 120px" type="submit" value="Drag 'n' throw me"> <input id="3" class="drag" style="width:100px; height:100px; top: 240px" type="submit" value="Drag 'n' throw me"> <pre id="debug"> </pre> </div> <script language="JavaScript" type="text/javascript"> <!-- //Kinetic moving script var x = "" var y = "" var i = 1 var dest_x = "" var dest_y = "" var date = new Date(); var time1=date.getTime(); var Xpos_diff = "" var Ypos_diff = "" var time_diff = "" var objID = "" function kinetic() { var dragobj = document.getElementById(objID); //Keep on moving the image till the target is achieved x = (x - dest_x) * 0.97 + dest_x; y = (y - dest_y) * 0.97 + dest_y; //Move the image to the new location dragobj.style.left = x+'px'; dragobj.style.top = y+'px'; if (i < 1) { window.setTimeout('kinetic()',10); } } //Drag and drop + thtow calculation___________________________________________________________________________________________________ function $(id){ return document.getElementById(id); } var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug = $('debug'); // makes life easier InitDragDrop(); function InitDragDrop() { document.onmousedown = OnMouseDown; document.onmouseup = OnMouseUp; } function OnMouseDown(e) { i = 1 // IE is retarded and doesn't pass the event object if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; objID = ExtractNumber(target.id) var dragobj = document.getElementById(objID); x=dragobj.style.left y=dragobj.style.top dest_x=dragobj.style.left dest_y=dragobj.style.top // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = x1 = ExtractNumber(target.style.left); _offsetY = y1 = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // we need to access the element in OnMouseMove _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; // prevent text selection (except IE) return false; } } function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; x=_offsetX + e.clientX - _startX y=_offsetY + e.clientY - _startY dest_x = _offsetX + e.clientX - _startX dest_y = _offsetY + e.clientY - _startY Xpos_diff = (_offsetX + e.clientX - _startX) - x1 Ypos_diff = (_offsetY + e.clientY - _startY) - y1 x1 = _offsetX + e.clientX - _startX y1 = _offsetY + e.clientY - _startY var date = new Date() var time2 = date.getTime(); time_diff = time2-time1 time1 = time2 } function OnMouseUp(e) { if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; dest_x = x + time_diff * Xpos_diff*3 dest_y = y + time_diff * Ypos_diff*3 i = 0 kinetic() } else{ i = 1 x=_dragElement.style.left y=_dragElement.style.top dest_x=_dragElement.style.left dest_y=_dragElement.style.top } } //--> function borders(){ if(x<0){ dest_x = 0 } else if(x>document.documentElement.clientWidth-100){ dest_x = document.documentElement.clientWidth-100 } if(y<0){ dest_y = 0 } else if(y>document.documentElement.clientHeight-100){ dest_y = document.documentElement.clientHeight-100 } window.setTimeout('borders()',10) } </script> </div> </body> </html> What need to be fixed is an small issue when start dragging the object and then stop moving while you still drag object, after release the mouse in still position the object will make a small move! And that must not happening! You will see by yourself what I meant, just drag and throw object! If you like it you are free to use it! All I want is someone to help fix this issue! Hello everyone! So, what it does: You can successfully drag something anywhere, but when you click it again, it resets to its original position (I don't know why), and when you try to drag it again, as soon as your cursor touches the object it disappears (I don't know why). I'm hoping someone can tell me why it is happening and how to fix it! Code: // JavaScript Document var posX; var posY; var element; function drag(event) { element = document.getElementById("square"); posX = event.clientX; posY = event.clientY; element.addEventListener("mousemove", move, false); } function move(event) { if (typeof(document.getElementById("square").mouseup) == "undefined") element.addEventListener("mouseup", drop, false); //Prevents redundantly adding the same event handler repeatedly element.style.left = event.clientX - posX + "px"; element.style.top = event.clientY - posY + "px"; } function drop() { element.removeEventListener("mousemove", move, false); element.removeEventListener("mouseup", drop, false); } the html is a simple (position is set to relative): <p id="square" onmousedown="drag(event)">meep</p> Lastly, and most importantly, thank you all for your time =] EDIT: This is the first time I've written javascript code and would like to learn the basics, which is why I am not using a library. Hello, I'm in need of help on my drag and drop code. How can I make 2 images (1 draggable, 1 static) each switch to alternate images when the draggable is dragged over the static?
Hey complete beginner to javascript here so sorry if I'm doing something stupid Basically I've tried to follow this guide to make it so that I can move an image on the page. I have a style tag in the head Code: <style type="text/css">.drag{position: relative;}</style> I have an image like this: Code: <img src="logo.png" class="drag" alt="logo" /> which is obviously in the body I copied and pasted the code given in the guide: Code: <script language="JavaScript" type="text/javascript"> <!-- var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug = $('debug'); // makes life easier InitDragDrop(); function InitDragDrop() { document.onmousedown = OnMouseDown; document.onmouseup = OnMouseUp; } function OnMouseDown(e) { // IE is retarded and doesn't pass the event object if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; _debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked'; // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = ExtractNumber(target.style.left); _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // we need to access the element in OnMouseMove _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; // prevent text selection (except IE) return false; } } function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')'; } function OnMouseUp(e) { if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; _debug.innerHTML = 'mouse up'; } } //--> </script> I have tried putting the javascript in the head and the body but no matter where I put it, I can't drag and drop the image. What am I doing wrong? Thank you for your time All I Want To Make Happen Is That If You Drag and Drop A Div Into A Table An Action Happens
Hello, I have a system where one clicks on an image an a floating calculator appear. <img src="images/groutculatorman.png" width="114" height="85" onclick="showdiv()"/> <div id="demo" style="visibility:hidden"> <div id="calculator" class="drag"> ----- <script type="text/javascript"> function closeCalculator() { document.getElementById("calculator").style.display = "none"; window.location.href = window.location.href;} var ie = document.all; var ns6 = document.getElementById && !document.all; var dragapproved=false; var z, x, y; function move(e) { if (dragapproved) { z.style.left=ns6? temp1+e.clientX-x: temp1+event.clientX-x; z.style.top=ns6? temp2+e.clientY-y : temp2+event.clientY-y; return false; } } function drags(e) { if (!ie&&!ns6) return; var firedobj = ns6? e.target : event.srcElement; var topelement = ns6? "HTML" : "BODY"; while (firedobj.tagName != topelement&&firedobj.className != "drag") { firedobj = ns6? firedobj.parentNode : firedobj.parentElement; } if (firedobj.className == "drag") { dragapproved = true; z = firedobj; temp1 = parseInt(z.style.left+0); temp2 = parseInt(z.style.top+0); x = ns6? e.clientX: event.clientX; y = ns6? e.clientY: event.clientY; document.onmousemove=move; return false; } } document.onmousedown=drags; document.onmouseup=new Function("dragapproved=false"); // --> function showdiv() { var mydiv = document.getElementById("demo"); mydiv.style.visibility=""; mydiv.style.display=""; } </script> ------ PROBLEM I added a drop down function on the image in order to open different calculators. The system works however the calculator won't drop (doesn't deselect). Any ideas. New code. <a href="javascript:;" onMouseOver="MM_showMenu(window.mm_menu_1009090908_0,11,82,null,'image1')" onMouseOut="MM_startTimeout();"> <img src="images/groutculatorman.png" name="image1" width="114" height="85" border="0" id="image1"> </a> <div id="demo" style="visibility:hidden"> <div id="calculator" class="drag"> ------------- <script language="JavaScript1.2">mmLoadMenus();</script> <script type="text/javascript"> <!-- function mmLoadMenus() { if (window.mm_menu_1009090908_0) return; window.mm_menu_1009090908_0 = new Menu("root",135,18,"Verdana, Arial, Helvetica, sans-serif",12,"#FF0000","#FFFFFF","#FFFFFF","#000084","left","middle",3,0,1000,-5,7,true,true,true,0,false,true); mm_menu_1009090908_0.addMenuItem("Baseplate","showdiv()"); mm_menu_1009090908_0.addMenuItem("Tank/Anchorbolt","showdiv2()"); mm_menu_1009090908_0.addMenuItem("Tank/Circumference","showdiv3()"); mm_menu_1009090908_0.hideOnMouseOut=true; mm_menu_1009090908_0.bgColor='#555555'; mm_menu_1009090908_0.menuBorder=1; mm_menu_1009090908_0.menuLiteBgColor='#FFFFFF'; mm_menu_1009090908_0.menuBorderBgColor='#777777'; mm_menu_1009090908_0.writeMenus(); } // mmLoadMenus() </script> function closeCalculator() { document.getElementById("calculator").style.display = "none"; window.location.href = window.location.href;} var ie = document.all; var ns6 = document.getElementById && !document.all; var dragapproved=false; var z, x, y; function move(e) { if (dragapproved) { z.style.left=ns6? temp1+e.clientX-x: temp1+event.clientX-x; z.style.top=ns6? temp2+e.clientY-y : temp2+event.clientY-y; return false; } } function drags(e) { if (!ie&&!ns6) return; var firedobj = ns6? e.target : event.srcElement; var topelement = ns6? "HTML" : "BODY"; while (firedobj.tagName != topelement&&firedobj.className != "drag") { firedobj = ns6? firedobj.parentNode : firedobj.parentElement; } if (firedobj.className == "drag") { dragapproved = true; z = firedobj; temp1 = parseInt(z.style.left+0); temp2 = parseInt(z.style.top+0); x = ns6? e.clientX: event.clientX; y = ns6? e.clientY: event.clientY; document.onmousemove=move; return false; } } document.onmousedown=drags; document.onmouseup=new Function("dragapproved=false"); // --> function showdiv() { var mydiv = document.getElementById("demo"); mydiv.style.visibility=""; mydiv.style.display=""; } </script> I'm sure that you must be sick and tired of the drag & drop question and for that I apologise but I have not been able to find an answer to this particular requirement despite much reading. The object of this task is to create a very limited editor in javascript. I have a page with two DIVs in columns. The left DIV holds text and the right holds several images. The DIVs are populated as the page loads. There are a couple of buttons used to apply styles to the selected text, heading or description. Looking like this :- Code: <div id="details"> <p class="heading">text</p> <p class="desc">text</p> <p class="heading">text</p> <p class="desc">text</p> <p class="heading">text</p> <p class="desc">text</p> </div> Once the text has been formatted as above, I want to be able to drag the images into place in the text like this :- Code: <div id="details"> <p class="heading">text</p> <p class="desc">text</p> <p class="heading"><img src="photo.jpg">text</p> <p class="desc">text</p> <p class="heading">text</p> <p class="desc">text</p> </div> The images in the left DIV have been given float right in css. I have not been able to find a method of placing that image in position like that. I guess it doesn't have to be drag&drop, but that would be far easer for the operator. Can anyone point me in the right direction please but I beg, please be gentle I am a newbie at javascript. Many thanks. Edited to add: This only needs to work in FF. Hi everyone I am having a bit of trouble with a question that I have been given for my Javascript assignment. I was given a web page with a series of boxes (created by <div> tags) which could be dragged and dropped anywhere on the web page, and they were dragged by holding the mouse down and dragging, and released when the mouse button was released. The web page can be viewed at http://adamr.hitwebs.net/dragDropOriginal.html and the source can be viewed at http://adamr.hitwebs.net/dragDropOriginal.js. The assignment was to make any other element drag-and-droppable, so I chose to make a jigsaw puzzle and hence make images drag-and-droppable, but with minimal changes to the script (simply changing the class name and id of my images), the dragging and dropping process is visually very different (the images appear to "stick" to the cursor on mouse up, and you have to actually click a second time to drop the image). Can someone please help me to fix this so that the drag and drop looks like what the boxes did (an example of what I want is exactly how the smiley faces are dragged-and-dropped at http://elouai.com/javascript-drag-and-drop.php). My jigsaw puzzle can be viewed at http://adamr.hitwebs.net/drag&Drop.html and the source can be downloaded from http://adamr.hitwebs.net/dragDrop.js. As you will see, apart from the large sections of script that I added, I only changed about two or three words of the original script, and it stopped working properly as soon as I started using images, which was long before I made my own additions to the script. Also note that there are A LOT of comments in my code because this is an assignment, and I have to note every change that I made to the original code, as well as put explanatory comments in my own code. P.S. Please don't tell me to use the script on the smiley face web page that I have provided, as this would not be useful to me. I must amend the script that I was originally given with the boxes. As for the assignment, I have checked this with the teacher, and I will not lose any marks for the terrible drag-and-drop effect as it does not appear to be my fault. This post is purely for my curiosity and because I hate not being able to solve a problem, and to me, this is a problem. Thanks heaps, - Adam I can't figure out how to drag and drop. I've followed some tutorials but no success. I use Firefox as my browser. Any tutorial you would recommend?
Hi Folks, I've been trying to create a drag drop homepage like www.bbc.co.uk, google etc. I can get the basic drag and drop to work, but I can't get the layout to save anywhere. Can anyone please help? Here is what I have so far. http://www.sandwell.nhs.uk/test/test.html It uses Glow, which doesn't have any cookie functions apparantly. Could anyone please help me save my layout, any example code would be much appreciated Manu thanks Hello CodingForums! I need some help with drag & drop links / downloads. I would like an example like the following website; http://panic.com/ |