Pure Javascript Drag and Drop cross browser from IE8

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:

<!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>
!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.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*