Techumber
Home Blog Work

Simple Draggable Element Using Pure JavaScript (No Jquery UI)

Published on March 31, 2014

Some times it’s very uncool to use whole librarys(JQuery and JQuery UI) for a single functionolity. One such functionality we often need is  Drggable object on a web page. Thought we can do it very easily JQuery UI, we need to download or CDN  them to your site. It will cost your bandwith as well as it will reduce pageload speed. If you want only a simple draggable functionality on one more element you can write your code very easily using only javascript. So, let’s start.

Demo

Download

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>
      Simple Draggable Element Using Pure JavaScript (No Jquery
      UI):techumber.com
    </title>
    <link rel="stylesheet" type="text/css" href="draggable.css" />
  </head>
  <body>
    <div id="drag">
      drag me
    </div>
  </body>
  <script type="text/javascript" src="draggable.js"></script>
  <script type="text/javascript">
    // calling your draggable function
    // you can use it without new also.
    // here drag is DOM element Id value
    new Draggable("drag");
  </script>
</html>

This is very simple html. Here we added our stylesheet and javascript files.

draggable.js

var Draggable = function(id) {
  var el = document.getElementById(id),
    isDragReady = false,
    dragoffset = {
      x: 0,
      y: 0
    };
  this.init = function() {
    //only for this demo
    el.style.position = "absolute";
    //this.initPosition();
    this.events();
  };
  //only for this demo
  this.initPosition = function() {
    el.style.top = "20px";
    el.style.left = "48%";
  };
  //events for the element
  this.events = function() {
    var self = this;
    _on(el, "mousedown", function(e) {
      isDragReady = true;
      //corssbrowser mouse pointer values
      e.pageX =
        e.pageX ||
        e.clientX +
          (document.documentElement.scrollLeft
            ? document.documentElement.scrollLeft
            : document.body.scrollLeft);
      e.pageY =
        e.pageY ||
        e.clientY +
          (document.documentElement.scrollTop
            ? document.documentElement.scrollTop
            : document.body.scrollTop);
      dragoffset.x = e.pageX - el.offsetLeft;
      dragoffset.y = e.pageY - el.offsetTop;
    });
    _on(document, "mouseup", function() {
      isDragReady = false;
    });
    _on(document, "mousemove", function(e) {
      if (isDragReady) {
        e.pageX =
          e.pageX ||
          e.clientX +
            (document.documentElement.scrollLeft
              ? document.documentElement.scrollLeft
              : document.body.scrollLeft);
        e.pageY =
          e.pageY ||
          e.clientY +
            (document.documentElement.scrollTop
              ? document.documentElement.scrollTop
              : document.body.scrollTop);
        el.style.top = e.pageY - dragoffset.y + "px";
        el.style.left = e.pageX - dragoffset.x + "px";
      }
    });
  };
  //cross browser event Helper function
  var _on = function(el, event, fn) {
    document.attachEvent
      ? el.attachEvent("on" + event, fn)
      : el.addEventListener(event, fn, !0);
  };
  this.init();
};

Here we created a simple Draggble Class. The technique for draggable element is pretty simple.If we combineing two events(mousedown,mousemove) into a single unit we will get draggable functionality. Few points you need to understand are, For all browser we use e.pageX get mouse pointer horizontal position. e.pageY to get mouse pointer vertical position. But for IE we need to add some extra code. We created ad crossbrowser event handling with **_on  ** function

draggable.css

* {
  border: 0;
  margin: 0;
  padding: 0;
}
html,
body {
  width: 100%;
  height: 100%;
}
#drag {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  background: #fcfcfc;
  line-height: 100px;
  text-align: center;
  cursor: move;
  background: #00a7c8;
  text-transform: uppercase;
}

This is very simple css code we use to simple  css reset and to style #drag div. If you want to have some smooth movement you can use css3 transition on the div.

-webkit-transition: all 1s;
-moz-transition: all 1s;
-ms-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;

Just add this code to the div in css.