Div Can Be Dragged

8

I would like to allow users to move some things from my site. Of the type, the user could drag the menu somewhere else to better position the reading.

    
asked by anonymous 17.05.2015 / 00:45

1 answer

16

There are several ways to do this, such as:

  • Javascript + CSS
  • Pure Javascript (no CSS, creates a "ghost" of the element)
  • And with frameworks like jQuery UI or interact.js

With javascript + CSS

See that I have used z-index so that the object stays ahead of the others when you have multiple elements

window.onload = function () {
    Dragable(document.getElementById("foo"));
    Dragable(document.getElementById("baz"));
    Dragable(document.getElementById("bar"));
};

//Adiciona eventos pra navegadores modernos e antigos
function addEvent(el, type, callback)
{
    if (el.addEventListener) {
       el.addEventListener(type, callback);
    } else if (el.attachEvent) {
       el.attachEvent("on" + type, callback);
    }
}

function Dragable(el)
{
    var isMove = false, //Verifica se esta se movendo
        x = 0, y = 0, //Pega as coordenadas do mouse
        xel = 0, yel = 0; // ultima posição do elemento

    addEvent(el, "mousedown", function (e) {
        isMove = true;

        el.className += " isMoving";

        x = window.event ? window.event.clientX : e.pageX;
        y = window.event ? window.event.clientY : e.pageY;

        xel = x - el.offsetLeft;
        yel = y - el.offsetTop;
    });

    addEvent(document, "mousemove", function (e) {
        if (isMove) {
            e.preventDefault();

            x = window.event ? window.event.clientX : e.pageX;
            y = window.event ? window.event.clientY : e.pageY;

            el.style.left = (x - xel) + 'px';
            el.style.top  = (y - yel) + 'px';
        }
    });

    addEvent(document, "mouseup", function () {
        el.className = String(el.className).replace(/(^|\s)isMoving(\s|$)/g, " ");
        isMove = false;
    });
};
#foo, #baz, #bar {
    position: absolute;
    z-index: 1000;
    width: 200px;
    height: 200px;
    background-color: #fc0;
}

.isMoving {
   z-index: 1001 !important;
}

#baz {
    top: 210px;
    left: 210px;
    background-color: #f00;
}

#bar {
    top: 410px;
    left: 410px;
    background-color: #00f;
}
<div id="foo"></div>
<div id="bar"></div>
<div id="baz"></div>

With native events (pure javascript) and event.dataTransfer :

In HTML we have the attributes ondragstart , ondrop and ondragover that serve for this purpose, but the browser creates a ghost image of the element as it drags, the element remains in place and only changes its place after the " drop ", note that this does not position by X and Y, but rather within other HTML elements.

function allowDrop(e) {
    e = e||window.event;

    e.preventDefault();
}

function drag(e) {
    e = e||window.event;

    e.dataTransfer.setData("text", e.target.id);
}

function drop(e) {
    e = e||window.event;
    e.preventDefault();
    var data = e.dataTransfer.getData("text");
    e.target.appendChild(document.getElementById(data));
}

var area1 = document.getElementById("drop-area-1");
var area2 = document.getElementById("drop-area-2");
var draggable = document.getElementById("draggable-item");

draggable.ondragstart = drag;
area1.ondrop = drop;
area1.ondragover = allowDrop;

area2.ondrop = drop;
area2.ondragover = allowDrop;
#draggable-item
{
    background-color: #fc0;
    width: 100px;
    height: 100px;
}

#drop-area-1, #drop-area-2
{
    display: inline-block;
    border: 1px #c0c0c0 solid;
    width: 200px;
    height: 200px;
    margin: 5px;
}
<div id="draggable-item" draggable="true"></div>

<div id="drop-area-1"></div>
<div id="drop-area-2"></div>

Using jQuery UI

jQuery has an additional library that can be downloaded from this link jQuery UI

$( "#draggable" ).draggable();
#draggable { width: 150px; height: 150px; padding: 0.5em; }
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<div id="draggable" class="ui-widget-content">
  <p>Clique e arraste</p>
</div>

Using interact.js

interact.js is a javascript library that supports resizing, moving, mobiles, etc.

// target elements with the "draggable" class
interact('.draggable')
  .draggable({
    // enable inertial throwing
    inertia: true,
    // keep the element within the area of it's parent
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },

    // call this function on every dragmove event
    onmove: dragMoveListener,
    // call this function on every dragend event
    onend: function (event) {
      var textEl = event.target.querySelector('p');

      textEl && (textEl.textContent =
        'moved a distance of '
        + (Math.sqrt(event.dx * event.dx +
                     event.dy * event.dy)|0) + 'px');
    }
  });

  function dragMoveListener (event) {
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
    target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

  // this is used later in the resizing demo
  window.dragMoveListener = dragMoveListener;
#drag-1, #drag-2 {
  width: 25%;
  height: 100%;
  min-height: 6.5em;
  margin: 10%;

  background-color: #29e;
  color: white;

  border-radius: 0.75em;
  padding: 4%;

  -webkit-transform: translate(0px, 0px);
          transform: translate(0px, 0px);
}

#drag-me::before {
  content: "#" attr(id);
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.4/interact.min.js"></script><divid="drag-1" class="draggable">
  <p> You can drag one element </p>
</div>
<div id="drag-2" class="draggable">
    <p> with each pointer </p>
</div>

How to insert JavaScript into HTML

You should do the following:

<!DOCTYPE html>
<html>
<head>
    <title>titulo</title>
    Coloque o arquivos .js e .css aqui
</head>
<body>
    Coloque o conteudo HTML aqui
</body>
</html>

An example should be something like jquery and jqueryui (in case I'm using CDN):

<!DOCTYPE html>
<html>
<head>
    <title>Titulo</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script><scriptsrc="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
    <div id="draggable" class="ui-widget-content">
        <p>Clique e arraste</p>
    </div>
</body>
</html>
    
17.05.2015 / 02:45