I was looking for a simple JavaScript to drag a div element around, and that would work with IE8 and without any third party libraries (like jQuery). It’s been very difficult to find a simple code !
Finally http://news.qooxdoo.org/mouse-capturing saved me with some code… but there was still a problem with IE8 due to the mouse that wasn’t losing capture. So after some research, I’ve been able to create a code that works for IE8 and modern browsers:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <! DOCTYPE html> < html > < head > </ head > < body > <!-- `top` and `left` must be defined into the `style` --> < div id = "popup" style = "background-color:green;position:absolute;top:0px;left:0px;width:250px;height:250px;z-index:9999;box-shadow: 6px 6px 5px #888888;border-radius:6px;border:1px solid #4f4f4f;" > < div id = "popup_bar" style = "width:100%;background-color:#aaff66;position:relative;top:0;border-radius:6px 6px 0 0; text-align:center;height:24px;cursor:move" >Title</ div > < p >Content of the popup</ p > </ div > </ body > < script >/* see below for the javascript */</ script > </ html > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | ! function () { function addListener(element, type, callback, capture) { if (element.addEventListener) { element.addEventListener(type, callback, capture); } else { element.attachEvent( "on" + type, callback); } } function draggable(element) { var dragging = null ; addListener(element, "mousedown" , function (e) { var e = window.event || e; dragging = { mouseX: e.clientX, mouseY: e.clientY, startX: parseInt(element.style.left), startY: parseInt(element.style.top) }; if (element.setCapture) element.setCapture(); }); addListener(element, "losecapture" , function () { dragging = null ; }); addListener(document, "mouseup" , function () { dragging = null ; if (document.releaseCapture) document.releaseCapture(); }, true ); var dragTarget = element.setCapture ? element : document; addListener(dragTarget, "mousemove" , function (e) { if (!dragging) return ; var e = window.event || e; var top = dragging.startY + (e.clientY - dragging.mouseY); var left = dragging.startX + (e.clientX - dragging.mouseX); element.style.top = (Math.max(0, top)) + "px" ; element.style.left = (Math.max(0, left)) + "px" ; }, true ); }; // here you must define the element to be draggable draggable(document.getElementById( "popup" )); }(); |
You can test this code with the demo or see it on Gist.