JavaScript - Success Finally! Javascript Drag 'n' Drop Kinetic Scrolling!
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! Similar TutorialsHi, 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 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. 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 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 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]
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?
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> 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
Dear forum Rather than use a library, I have attempted to write my own attempt at a script that allows multiple elements to be dragged around the page. It starts by loading all divs into an array, and then forms a new array of only divs with the required class name. I believe this script doesn't work for internet explorer, but I am not concerned by this. As you will see if you run the code below, the script works well for divs containing text, but if I include an image inside a div, then the image will follow the mouse even if the button is released. I have spent a whole day on this tiny script and really don't know where to go from here! Could anybody shed some light on this please? Thanks Matt Code: <html> <head> <style> .dragger { background-color:lightgreen; position:absolute; } </style> <script type="text/javascript"> var all_els=[]; var els=[]; var el; window.onload = function() { all_els=document.getElementsByTagName("div"); //an array of all div elements on page for(var i=0;i<all_els.length;i++){ if(all_els[i].className=='dragger') { els.push(all_els[i]);} //just add those with the correct class name to our final array } for (el in els) { this.dragging=false; //each element in the array is an object, so new properties e.g. dragging can be set. Initially set the dragging property of each element to false els[el].onmousedown=function() {this.dragging=true;} els[el].onmouseup=function() {this.dragging=false;} } } document.onmousemove = function(e) { for(el in els) { if (els[el].dragging==true) { els[el].style.left = e.clientX - els[el].offsetWidth/2 +'px'; els[el].style.top = e.clientY - els[el].offsetHeight/2+'px'; } } } </script> <title>Simple Drag</title> </head> <body> <div class="dragger"> Some text to drag </div> <br><br><br><br><br><br> <div class="dragger"> Some other text to drag </div> <br><br><br><br><br><br> <div class="dragger"> <img src="http://www.mpklein.co.uk/images/phoenix.jpg"></img> </div> </body> </html> 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. Dear forum Rather than use a library, I have attempted to write my own attempt at a script that allows multiple elements to be dragged around the page. It starts by loading all divs into an array, and then forms a new array of only divs with the required class name. I believe this script doesn't work for internet explorer, but I am not concerned by this. As you will see if you run the code below, the script works well for divs containing text, but if I include an image inside a div, then the image will follow the mouse even if the button is released. I have spent a whole day on this tiny script and really don't know where to go from here! Could anybody shed some light on this please? Thanks Matt Code: <html> <head> <style> .dragger { background-color:lightgreen; position:absolute; } </style> <script type="text/javascript"> var all_els=[]; var els=[]; var el; window.onload = function() { all_els=document.getElementsByTagName("div"); //an array of all div elements on page for(var i=0;i<all_els.length;i++){ if(all_els[i].className=='dragger') { els.push(all_els[i]);} //just add those with the correct class name to our final array } for (el in els) { this.dragging=false; //each element in the array is an object, so new properties e.g. dragging can be set. Initially set the dragging property of each element to false els[el].onmousedown=function() {this.dragging=true;} els[el].onmouseup=function() {this.dragging=false;} } } document.onmousemove = function(e) { for(el in els) { if (els[el].dragging==true) { els[el].style.left = e.clientX - els[el].offsetWidth/2 +'px'; els[el].style.top = e.clientY - els[el].offsetHeight/2+'px'; } } } </script> <title>Simple Drag</title> </head> <body> <div class="dragger"> Some text to drag </div> <br><br><br><br><br><br> <div class="dragger"> Some other text to drag </div> <br><br><br><br><br><br> <div class="dragger"> <img src="http://www.mpklein.co.uk/images/phoenix.jpg"></img> </div> </body> </html> Hi. I'm trying to get drag and drop script working from this tutorial: http://www.webreference.com/programm...mn2/index.html I want to drag items between columns (DIV's). Here is my code: Code: document.onmousemove = mouseMove; document.onmouseup = mouseUp; document.onmousedown = mouseDown; window.onload = function(){ // Create our helper object that will show the item while dragging dragHelper = document.createElement('DIV'); dragHelper.style.cssText = 'position:absolute;display:none;'; CreateDragContainer( document.getElementById('DragContainer1'), document.getElementById('DragContainer2'), document.getElementById('DragContainer3') ); document.body.appendChild(dragHelper); } var mouseOffset = null; var iMouseDown = false; var lMouseState = false; var dragObject = null; // Demo 0 variables var DragDrops = []; var curTarget = null; var lastTarget = null; var dragHelper = null; var tempDiv = null; var rootParent = null; var rootSibling = null; function mouseCoords(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; } document.onmouseup = mouseUp; var dragObject = null; function makeClickable(object){ object.onmousedown = function(){ dragObject = this; } } var dropTargets = []; function addDropTarget(dropTarget){ dropTargets.push(dropTarget); } function mouseUp(ev){ ev = ev || window.event; var mousePos = mouseCoords(ev); for(var i=0; i<dropTargets.length; i++){ var curTarget = dropTargets[i]; var targPos = getPosition(curTarget); var targWidth = parseInt(curTarget.offsetWidth); var targHeight = parseInt(curTarget.offsetHeight); if( (mousePos.x > targPos.x) && (mousePos.x < (targPos.x + targWidth)) && (mousePos.y > targPos.y) && (mousePos.y < (targPos.y + targHeight))){ // dragObject was dropped onto curTarget! } } dragObject = null; } var dragObject = null; var mouseOffset = null; function getMouseOffset(target, ev){ ev = ev || window.event; var docPos = getPosition(target); var mousePos = mouseCoords(ev); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; } function getPosition(e){ var left = 0; var top = 0; while (e.offsetParent){ left += e.offsetLeft; top += e.offsetTop; e = e.offsetParent; } left += e.offsetLeft; top += e.offsetTop; return {x:left, y:top}; } function mouseMove(ev){ ev = ev || window.event; /* We are setting target to whatever item the mouse is currently on Firefox uses event.target here, MSIE uses event.srcElement */ var target = ev.target || ev.srcElement; var mousePos = mouseCoords(ev); // mouseOut event - fires if the item the mouse is on has changed if(lastTarget && (target!==lastTarget)){ // reset the classname for the target element var origClass = lastTarget.getAttribute('origClass'); if(origClass) lastTarget.className = origClass; } /* dragObj is the grouping our item is in (set from the createDragContainer function). if the item is not in a grouping we ignore it since it can't be dragged with this script. */ var dragObj = target.getAttribute('DragObj'); // if the mouse was moved over an element that is draggable if(dragObj!=null){ // mouseOver event - Change the item's class if necessary if(target!=lastTarget){ var oClass = target.getAttribute('overClass'); if(oClass){ target.setAttribute('origClass', target.className); target.className = oClass; } } // if the user is just starting to drag the element if(iMouseDown && !lMouseState){ // mouseDown target curTarget = target; // Record the mouse x and y offset for the element rootParent = curTarget.parentNode; rootSibling = curTarget.nextSibling; mouseOffset = getMouseOffset(target, ev); // We remove anything that is in our dragHelper DIV so we can put a new item in it. for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]); // Make a copy of the current item and put it in our drag helper. dragHelper.appendChild(curTarget.cloneNode(true)); dragHelper.style.display = 'block'; // set the class on our helper DIV if necessary var dragClass = curTarget.getAttribute('dragClass'); if(dragClass){ dragHelper.firstChild.className = dragClass; } // disable dragging from our helper DIV (it's already being dragged) dragHelper.firstChild.removeAttribute('DragObj'); /* Record the current position of all drag/drop targets related to the element. We do this here so that we do not have to do it on the general mouse move event which fires when the mouse moves even 1 pixel. If we don't do this here the script would run much slower. */ var dragConts = DragDrops[dragObj]; /* first record the width/height of our drag item. Then hide it since it is going to (potentially) be moved out of its parent. */ curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth)); curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight)); curTarget.style.display = 'none'; // loop through each possible drop container for(var i=0; i<dragConts.length; i++){ with(dragConts[i]){ var pos = getPosition(dragConts[i]); /* save the width, height and position of each container. Even though we are saving the width and height of each container back to the container this is much faster because we are saving the number and do not have to run through any calculations again. Also, offsetHeight and offsetWidth are both fairly slow. You would never normally notice any performance hit from these two functions but our code is going to be running hundreds of times each second so every little bit helps! Note that the biggest performance gain here, by far, comes from not having to run through the getPosition function hundreds of times. */ setAttribute('startWidth', parseInt(offsetWidth)); setAttribute('startHeight', parseInt(offsetHeight)); setAttribute('startLeft', pos.x); setAttribute('startTop', pos.y); } // loop through each child element of each container for(var j=0; j<dragConts[i].childNodes.length; j++){ with(dragConts[i].childNodes[j]){ if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue; var pos = getPosition(dragConts[i].childNodes[j]); // save the width, height and position of each element setAttribute('startWidth', parseInt(offsetWidth)); setAttribute('startHeight', parseInt(offsetHeight)); setAttribute('startLeft', pos.x); setAttribute('startTop', pos.y); } } } } } // If we get in here we are dragging something if(curTarget){ // move our helper div to wherever the mouse is (adjusted by mouseOffset) dragHelper.style.top = mousePos.y - mouseOffset.y; dragHelper.style.left = mousePos.x - mouseOffset.x; var dragConts = DragDrops[curTarget.getAttribute('DragObj')]; var activeCont = null; var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2); var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2); // check each drop container to see if our target object is "inside" the container for(var i=0; i<dragConts.length; i++){ with(dragConts[i]){ if(((getAttribute('startLeft')) < xPos) && ((getAttribute('startTop')) < yPos) && ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) && ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){ /* our target is inside of our container so save the container into the activeCont variable and then exit the loop since we no longer need to check the rest of the containers */ activeCont = dragConts[i]; // exit the for loop break; } } } // Our target object is in one of our containers. Check to see where our div belongs if(activeCont){ // beforeNode will hold the first node AFTER where our div belongs var beforeNode = null; // loop through each child node (skipping text nodes). for(var i=activeCont.childNodes.length-1; i>=0; i--){ with(activeCont.childNodes[i]){ if(nodeName=='#text') continue; // if the current item is "After" the item being dragged if( curTarget != activeCont.childNodes[i] && ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) && ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){ beforeNode = activeCont.childNodes[i]; } } } // the item being dragged belongs before another item if(beforeNode){ if(beforeNode!=curTarget.nextSibling){ activeCont.insertBefore(curTarget, beforeNode); } // the item being dragged belongs at the end of the current container } else { if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){ activeCont.appendChild(curTarget); } } // make our drag item visible if(curTarget.style.display!=''){ curTarget.style.display = ''; } } else { // our drag item is not in a container, so hide it. if(curTarget.style.display!='none'){ curTarget.style.display = 'none'; } } } // track the current mouse state so we can compare against it next time lMouseState = iMouseDown; // mouseMove target lastTarget = target; // track the current mouse state so we can compare against it next time lMouseState = iMouseDown; // this helps prevent items on the page from being highlighted while dragging return false; } function mouseUp(ev){ if(curTarget){ // hide our helper object - it is no longer needed dragHelper.style.display = 'none'; // if the drag item is invisible put it back where it was before moving it if(curTarget.style.display == 'none'){ if(rootSibling){ rootParent.insertBefore(curTarget, rootSibling); } else { rootParent.appendChild(curTarget); } } // make sure the drag item is visible curTarget.style.display = ''; } curTarget = null; iMouseDown = false; } function mouseDown(){ iMouseDown = true; if(lastTarget){ return false; } } function makeDraggable(item){ if(!item) return; item.onmousedown = function(ev){ dragObject = this; mouseOffset = getMouseOffset(this, ev); return false; } } Number.prototype.NaN0=function(){return isNaN(this)?0:this;} function CreateDragContainer(){ /* Create a new "Container Instance" so that items from one "Set" can not be dragged into items from another "Set" */ var cDrag = DragDrops.length; DragDrops[cDrag] = []; /* Each item passed to this function should be a "container". Store each of these items in our current container */ for(var i=0; i<arguments.length; i++){ var cObj = arguments[i]; DragDrops[cDrag].push(cObj); cObj.setAttribute('DropObj', cDrag); /* Every top level item in these containers should be draggable. Do this by setting the DragObj attribute on each item and then later checking this attribute in the mouseMove function */ for(var j=0; j<cObj.childNodes.length; j++){ // Firefox puts in lots of #text nodes...skip these if(cObj.childNodes[j].nodeName=='#text') continue; cObj.childNodes[j].setAttribute('DragObj', cDrag); } } } This script is working only particularly as You can see he http://lukasz.webh.pl/test.html Can anyone tell me please what is wrong with this script? Hi everyone, I am setting up a website where we want a drag n drop solution for a customer to place an email. To give you an idea on what we want, picture this... A form where the customer can enter there details. Below the form are icons of items. The customer can then drag these items into an image of a box below. Would also be nice if it could list what is "in" the box. Once customer is satisfied, the contents get emailed to us and we can provide further details from there. Mainly has to look nice from the customers side, on our side we are happy to receive just the titles or codes of what they are dragging into this box. Hopefully i have made this simple to understand, if anyone needs any more information, please do not hesitate to ask me. Also, this will be implemented into a Joomla site once sorted out, if that makes any difference. Thank you in advance! I am creating a website that runs an iFrame with website displayed in it. On that page, in the frame, there is a simple href hyperlink. I have a text element next to the iFrame that is acting as an address bar. I want to be able to drag the link from the frame to the address bar and ondrop have the iframe redirect to the dragged link url. Here is the code I have Code: <html> <head> <style> #NetFrame { border:2px solid #0A9; height:650px; width:75%; Position: absolute; top:2%; left:25%; } #url { width:25%; height:650px; } </style> <script type="text/javascript"> function getUrl() { var source = document.getElementById('url').value; loadUrl(source); } function loadUrl(source) { var showUrl = document.getElementById('NetFrame'); NetFrame.src = source; document.getElementById('url').value=""; } </script> </head> <body> <form> <input type="text" id="url" onDragEnd="getUrl()"/> </form> <iframe src="link1.html" id="NetFrame"> </iframe> </body> </html> The iFrame is called NetFrame and the Text element is url. I have not coded in 6 years and am stuck here. Please Help, and be specific you are explaining to an absolute novice. |