This is more of a theoretical question which I hope is okay!? I want to code my own drag and drop jQuery plugin, but i'm wondering the best way to go about structuring my code and actually doing it.

Note: This MAY be opinion orientated as well but I don't mind, I just need suggestions on a good way to go about this and structuring the code etc.

Current plan:

Item Class: I want to use Object Orientated Programming here, so was going to store the reference to each draggable item in an instance of a class, which are in turn stored within an array. Then within this class I can do calculations based on that draggable item.

When to capture mousemove: To save on computing power incase of other JavaScript intensive scripts I was thinking about only capturing any mouse movements when the mouse is down on an item.

Actually moving items: Well, I will just change the items position to fixed/absolute and adjust the top and left values, what happens on release I cover below.

Moving items out of the way to place selected, and actually dropping an item in a new location: That's a long bolded one! But yeah, i'm not too sure on how I would go about this! Basically I would have a list of li's which I want to re-order, but as I move an item to a new position I want the other items to slide out of the way smoothly, preferably using transforms as to pass the animation over to the GPU.

Moving items into other stacks: Some of my li's may have ul's within then, I need the ability to detect when the draggable item is being attempted to be dropped into another item. If this makes sense! :(

Kinda example structure of my items?

<ul id="sortable">
  <li id="1">Home</li>
  <li id="2">Showroom
  <li id="3">Finance</li>
  <li id="4">Servicing</li>
  <li id="5">About Us</li>
  <li id="6">Contact</li>

I have sort of started some of the code, however I don't want to do too much if i'm going about it all wrong!

/* Global Javascript */
(function($) {
  $.fn.draggable = function() {
    // Establish our default settings
    var settings = $.extend({ }, options);

    class Item {
      constructor(obj) {
        this.elm = obj;

      // Return the items dimentions
      getDimentions() {
        return new array((this.obj).outerWidth(), (this.obj).outerHeight());
    // Store draggable items
    var $items = new Array();
    $(this).each() {
      if ($(this).is('li')) {
        $items[] = new Item($(this));

    var $dragObject = null;
    function makeClickable(object) {
      object.onmousedown = function() {
        $dragObject = this;
    function mouseUp(ev) {
      $dragObject = null;
  • Have you thought about looking at, say, how jQueryUI does it? Jan 2, 2017 at 18:17
  • check out Packery Feb 4, 2017 at 10:25


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.