JavaScript - Drag And Scroll Images
hi all, i dont know exactly how to explain this but ill give it a go.
What im looking for is to have a database hold a list of images ( or numbers that corrospond to images)... that should be easy enough. The part im having trouble with is having these images aligned in a grid which is inside a window /frame/ box on the web page. The user can click and drag and it will move around this collection of images..... like so (numbers represent images): 5 4 3 6 1 2 7 8 9 so if the user clicked and dragged to the right the images would then look like: 4 3 12 1 2 11 8 9 10 the new images are taken from the database and the user can drag in any direction. i hope that makes sence, can someone help with this ? even if its just what this is called that i should search for, ive tried draggable images, scrolling images etc etc thanks P.s like google maps Similar TutorialsAll, I'm trying to create a calendar application that users can upload pictures and then put them on a calendar. I'd like to display all of the images and then drag them from one pane to the calendar. I'd like it to be something similar to the following link: http://www.vistaprint.com/studio/cal...id=button&rd=2 Does anyone have any scripts that can do the drag and drop or could you possibly give me an idea on where to start with something like this? I really appreciate the help in advance! Thanks! Firstly, I'm not trying to 'fix' the code below. (eg: not interested in links to other drag & drop scripts). I'm mearly trying to understand what's happening & what I've missed or done wrong. For instance, why in FF & IE does it wait until after onmouseup (release) before moving the object, because it works fine with a DIV with only text in it, but not with a DIV with an image in it, or a stand alone image. In Chrome it seems to highlight the image and onmousemove also highlights the surrounding areas. I've tried forcing focus() & blur() & covering with a higher zIndexed transparent DIV but nothing seems to work. Any help in understanding would be greatly appreciated. dragscript.js Code: document.onmousemove = mouseXY; document.onmousedown = mouseDown; document.onmouseup = mouseUp; var mouseX = 0; var mouseY = 0; var drag; var dragObject = null; var mouseOffsetX; var mouseOffsetY; function mouseXY(e) { e = e || window.event; if (e.pageX || e.pageY) { mouseX = e.pageX; mouseY = e.pageY; } else if (e.clientX || e.clientY) { mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } document.getElementById('mouseposX').value = mouseX; document.getElementById('mouseposY').value = mouseY; if (dragObject) { document.getElementById(dragObject.id).style.left = mouseX - mouseOffsetX; document.getElementById(dragObject.id).style.top = mouseY - mouseOffsetY; } } function mouseDown(x) { if (!x) var x = window.event; if (x.target) drag = x.target; else if (x.srcElement) drag = x.srcElement; if (drag.nodeType == 3) drag = drag.parentNode; if (drag.className == 'dragable') { dragObject = drag; document.getElementById('ObjectId').value = dragObject.id; mouseOffsetX = mouseX - document.getElementById(dragObject.id).offsetLeft; mouseOffsetY = mouseY - document.getElementById(dragObject.id).offsetTop; } } function mouseUp() { dragObject = null; document.getElementById('ObjectId').value = ''; } test.html Code: <html> <head> <META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1"> <META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript"> <META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css"> <script type="text/javascript" src="dragscript.js"></script> <style type="text/css"> .dragable {position:absolute; left:200; top:200; border:2px solid black;} </style></head><body> MouseX : <input id="mouseposX" type="text" size=3> MouseY : <input id="mouseposY" type="text" size=3> dragObject Id : <input id="ObjectId" type="text" size=10> <image id="image1" class="dragable" src="test.gif" border=0> </body></html> Many thanks, Paul PS: Login for posting timeout too short. I 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 Hey everyone! I'm in the process of creating a portfolio site for my artwork and I'm requesting help. The website has a scalable JQuery background which changes depending on which thumbnail you click. I've uploaded the progress he http://www.aldousmassie.com/newprogress I'm using this code at the moment to scroll through the background: Code: <!-- SCRIPT FOR CHANGING BG ON CLICK --> <script type="text/javascript"> imgs=Array("img/00.jpg","img/01.jpg","img/02.jpg","img/03.jpg"); var x=0; function change() { document.getElementById("bgimg").src=imgs[++x]; if (x==3) { x=-1; } } if (!imgs[x+1]) { x=-1; } </script> <!-- SCRIPT BELOW OVERWRITES SCRIPT ABOVE --> <script type="text/javascript"> imgs=Array("img/08.jpg","img/09.jpg","img/10.jpg","img/11.jpg","img/12.jpg","img/13.jpg"); var x=0; function change() { document.getElementById("bgimg").src=imgs[++x]; if (x==5) { x=-1; } } if (!imgs[x+1]) { x=-1; } </script> Unfortunately, the bottom code overwrites the top. Is it possible for each different background image to have their own "set" of images that could be scrolled through onclick? I'd appreciate any tips that point me in the right direction. Thank you. I'm trying to make my sidebar show 3 images then scroll to the next 3 automatically every 3 seconds or so. (vertically) Can anyone help me out with a reference I could look at how to do it or show a snippet of code? I've looked up various scripts for scrolling the pictures I have on the right vertically, but I can't seem to implement any of the ones I've found. I'm not trying to ask for you to code it all for me (unless you really want to), but just need some help! Thanks! Here's the site: www.beunthinkable.org Hi All, I'm new to the CF forums and also to JavaScript. Trying to get a pop-up div to be draggable, but it doesn't seem to be working. Can someone help me out? I'd be very grateful! JavaScript I'm using: Code: //used for dragging div function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); } function xy(e,v) { return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX)); } function dragOBJ(d,e) { function drag(e) { if(!stop) { d.style.top=(tX=xy(e,1)+oY-eY+'px'); d.style.left=(tY=xy(e)+oX-eX+'px'); } } var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop; document.onmousemove=drag; document.onmouseup=function() { stop=1; document.onmousemove=''; document.onmouseup=''; }; } //used for pop-up div function pop(div) { document.getElementById(div).style.display='block'; return false } function hide(div) { document.getElementById(div).style.display='none'; return false } Also, here is the HTML: Code: <a href="#" onclick="return pop('myDiv2')">Pop-up div #2</a> - Hidden div shows upon clicking this link, but it won't drag <div class="bubble" onmousedown="dragOBJ(this,event); return false;"> <div id="myDiv2" class="parentDisable"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <p><a href="#" onClick="return hide('myDiv2')">Close [X]</a></p> </div> </div> And the CSS: Code: .parentDisable { position:absolute; margin:120px; padding:20px; width:400px; display:none; z-index:3; background-color:#DEDEDE; border:1px solid #DEDEDE; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; } .bubble { position:fixed; width:400px; top:150px; left:250px; cursor:move; } 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 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> hi, i want to drag the div which have a image in it: but i find that if i click on the image, i cannot drag the div, (in FF3.5) any advice would be appreciated. Code: <div id="div1"> <imc src="XXX.jpg"> </div> and i have a JS something like that...: Code: drag(); function drag(){ document.onmousedown = startdrag; document.onmouseup = enddrag; } function startdrag(e){ dragobj=e.target; alert(dragobj.id); } ...................... There seems to be a lot out there, but I haven't found a javascript for a click and drag that has been bug free. Does anyone have any suggestions? The last one I had didn't work in Safari. Thanks so much for any help. Hei, I should start by saying that I am very new in Javascript.. what I need to do is to drag the entire window...any ideas how to do that ? Thanks All I Want To Make Happen Is That If You Drag and Drop A Div Into A Table An Action Happens
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?
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 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. 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 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! http://www.javascriptkit.com/howto/drag.shtml Has anyone modified this script to drag multiple items? 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 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? |