JavaScript - Javascript Drag And Drop On A Fixed Location
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 Similar TutorialsHi, 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. 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> 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 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 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. 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 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> 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 CodingForums! I need some help with drag & drop links / downloads. I would like an example like the following website; http://panic.com/ 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 I am trying to loop through each area and checking if they match the image class number then it should drop in correct place. You can see that i commented out the loop and if statement because it doesn't work. Can anyone shine light on this because i'm frustrated with this issue. Code: $(document).ready(function(){ var images = $('#clothes').find('img'); var drop = $('#dress').find('area'); for(var a=0; a < images.length; a++){ $( images[a] ).draggable( ); //alert($(images[i]).hasClass("20")); if($(images[a]).hasClass("20")){ $( images[a] ).draggable({ revert: 'valid' }); //alert("WRONG"); } else{ $( images[a] ).draggable({ revert: 'invalid' }); } /*for(var b=0; b < drop.length; b++){ $( drop[k]).droppable({ activeClass: "ui-state-hover", hoverClass: "ui-state-active", drop: function( event, ui ) { $( this ).addClass( "ui-state-highlight" ) /*if($(images[a]).attr('class').split(" ")[0] == $(drop[b]).attr('class')){ alert("RIGHT"); $(images[a]).draggable({ revert: 'invalid' }); } else if($(images[a]).hasClass("20")){ $( images[a] ).draggable({ revert: 'valid' }); } //alert("a = " + $(images[a]).attr('class').split(" ")[0] + " b = " + $(drop[b]).attr('class')); } }); }*/ } }); Hi I need a help with my code. When i'm trying to put a picture in empty div it works fine, but when i put the second picture to the div where already is picture, then second picture "disappear". If i have only one div, then everything is ok, but with 2 or more divs i have issue. PHP Code: <div id="drop" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="drop2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <img id="drag1" src="http://images.photo.bikestats.eu/zdjecie,600,79346,20091201,zdjecia-wiewiorek.jpg" draggable="true" ondragstart="drag(event)" width="80" height="80"> <img id="drag2" src="http://www.tech-blog.pl/wordpress/wp-content/uploads/2011/12/gaba-16-12-2011.jpg" draggable="true" ondragstart="drag(event)" width="80" height="80"> <style> #drop { border: 1px solid black; width:80px; height:80px; } #drop2 { border: 1px solid black; width:80px; height:80px; } </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text/html", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text/html"); var parent = ev.target.parentNode; if( parent.id == 'drop' ) { parent.removeChild(ev.target); parent.appendChild(document.getElementById(data)); } else ev.target.appendChild(document.getElementById(data)); } </script> Hi all, I'm currently developing a drag on drag editor at work. I have a list of fields on the right which I drag onto a form and it adds the input object onto the form. I also have editable divs which I using to add text as a kind of very scaled down RTE. Rather than dragging a field the form, I could use the field as display only so I would like to embed this into the editable div as part the text. I'm thinking I could do something like facebook does where if I type a "@" then I could create a auto suggest to embed a field value into text but what i would like to do is drag the field into the text. So my question is this, is it possible to know the positon in the text of where I performed the drop, I suppose that would be where the mouseup occurs? Any thoughts much appericated, Thanks, Dale 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?
|