Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

drag&drop of div element

I have a rectangular div element on a page with image and text span inside. Div has 2px border to make it actually visible.

Then I add dragstart event listener to my div element. dragstart event fires always if I start dragging the image inside div but it is very problematic if I start dragging by clicking on text span or blank place:

In Google Chrome dragging is very unstable. It can work a few times then stops firing, then work again and so on. In Mozilla Firefox it doesn't work at all.

How to fix it and allow drag by clicking on any point inside bound rect of my div?

<div class="item">
  <img src="https://www.wigwam3d.com/previews/1f/1ffbf8da-a4d0-4e40-b9e1-0329220969dc.jpg">
  <div>Element</div>
</div>

Plunker: http://plnkr.co/edit/673ytif50cViE5dTv3df?p=preview

Upvotes: 0

Views: 74

Answers (2)

Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

Just found a simple solution: add attribute draggable=true on div element! That's all!

Upvotes: 0

Arun lama
Arun lama

Reputation: 46

Use this code , you can drag div anywhere on the window. Also fix width and height of the div.

$(function(){ $("#animation").css({"cursor":"move"})

// mousedown:fn(){dragging = true;}


var dragging = false;
var iX, iY;
$("#animation").mousedown(function(e) {
    dragging = true;
    iX = e.clientX - this.offsetLeft;
    iY = e.clientY - this.offsetTop;
    this.setCapture && this.setCapture();
    return false;
});

// mouseover:fn(){dragging = tru;}

document.onmousemove = function(e) {
    if (dragging) {
        var e = e || window.event;
        var oX = e.clientX - iX;
        var oY = e.clientY - iY;
        $("#animation").css({"left":oX + "px", "top":oY + "px"});
        return false;
    }
};

// mouseup:fn(){dragging = false;}

$('#animation').mouseup(function(e) {
    dragging = false;
    this.releaseCapture && this.releaseCapture();
    e.cancelBubble = true;
})

})

Upvotes: 1

Related Questions