Make Div Draggable Using CSS

Make Div Draggable using CSS

This is the best you can do without JavaScript:

[draggable=true] {  cursor: move;}
.resizable { overflow: scroll; resize: both; max-width: 300px; max-height: 460px; border: 1px solid black; min-width: 50px; min-height: 50px; background-color: skyblue;}
<div draggable="true" class="resizable"></div>

How to build a drag scenario using CSS or JS

For the inner div being out of bound issues add margin in the direction of the out of bounding in your case try adding margin-right: 35% for the #map div. For the smoothing behavior modify the ui.position property inside the drag callback. Keep on adjusting the added value to get the needed smoothing. (I subtracted 7 in both just as an example).

$("#map").draggable({
drag: function(event, ui) {
ui.position.left = ui.position.left-7;
ui.position.top = ui.position.top-7;
}
});

How to make a div draggable on another div?

Based on your html : Add this script

$( ".text-canvas"").draggable({
containment: ".imageupload"
});

For any doubts in syntax or working check these documents

(1) http://api.jqueryui.com/draggable/

(2) https://jqueryui.com/draggable/

Make sure you already included jquery-ui.js . First you need to call jquery.js or jquery.min.js then only call jquery-ui.js , the order is important.
eg:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Make a div, containing an img draggable

This is many years later, but I ran into the same problem, and finally figured it out.

An image is draggable by default, so when you drag an image in a div, the image gets dragged. All you have to do is the make the image non-draggable by:

<img draggable="false" src={status} />

Now when you drag the div, the div and its contained image are dragged together.

Make div draggable in a particular position

here is the UPDATED code you requested, You can change position and style of the box using CSS

     <style>
div
{
margin-bottom:10px;
height:100px;
}
.container
{
height:500px;
}
.col-md-6,.col-md-5
{
border:1px solid #000;
}
#div1,#div2,#div3,#div4,#div5 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>

<div class="container" id="container">
<div class="row">
<div class="col-md-offset-3 col-md-5">
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="drag1" src="http://www.w3schools.com/html/img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69" />
</div>
</div>
<div class="col-md-6">
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="drag2" src="http://jqueryui.com/jquery-wp-content/themes/jquery/content/books/jquery-ui-in-action.jpg" draggable="true" ondragstart="drag(event)" width="336" height="69" />
</div>
</div>
<div class="col-md-6">
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>
<div class="col-md-6">
<div id="div4" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>
<div class="col-md-6">
<div id="div5" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>
</div>

</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");

if(ev.target.tagName!="IMG"){
ev.target.appendChild(document.getElementById(data));
}
else{
var _oldDiv= document.getElementById(data).parentNode,
_oldData= document.getElementById(data),

_newDiv=ev.target.parentNode,
_newData=ev.target;

_oldDiv.appendChild(_newData);
_newDiv.appendChild(_oldData);

}

}
</script>

you can check this in Fiddle

How to make draggable div elements not stack upon each other

Answer: The key approach/solution is Collision Detection between div elements

It looks like you are trying to do a game or something similar, please save your self the pain/don't reinvent the wheel :) , just leverage a library and look for collision detection or set Z index to 1 and check of over lap, I prefer the sat.js lib.

note: Here is sat.js and look at this sample from here from a 3rd party/credit to OSU blake

console.clear();
var log = console.log.bind(console);

// Alias a few things in SAT.js to make the code shorter
var V = function (x, y) { return new SAT.Vector(x, y); };
var P = function (pos, points) { return new SAT.Polygon(pos, points); };
var C = function (pos, r) { return new SAT.Circle(pos, r); };
var B = function (pos, w, h) { return new SAT.Box(pos, w, h); };

// Converts a SAT.Polygon into a SVG path string.
function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + (pos.y + point.y);
}
result += 'Z';
return result;
}

// Create a Raphael start drag handler for specified entity
function startDrag(entity) {
return function () {
this.ox = entity.data.pos.x;
this.oy = entity.data.pos.y;
};
}
// Create a Raphael move drag handler for specified entity
function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
}
// Create a Raphael end drag handler for specified entity
function endDrag(entity) {
return function () {
entity.updateDisplay();
};
}

var idCounter = 0;

function noop() {}

function Entity(data, display, options) {
options = _.defaults(options || {}, {
solid: false, // Whether this object is "solid" and therefore should participate in responses.
heavy: false, // Whether this object is "heavy" and can't be moved by other objects.
displayAttrs: {}, // Raphael attrs to set on the display object
onCollide: noop, // Function to execute when this entity collides with another - arguments are (otherEntity, response)
onTick: noop // Function called at the start of every simulation tick - no arguments
});
this.id = idCounter++;
this.data = data;
this.display = display;
this.displayAttrs = _.extend({
fill: '#CCC',
stroke: '#000'
}, options.displayAttrs);
this.isSolid = options.solid;
this.isHeavy = options.heavy;
this.onCollide = options.onCollide;
this.onTick = options.onTick;
}
Entity.prototype = {
remove: function () {
this.display.remove();
},
// Call this to update the display after changing the underlying data.
updateDisplay: function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
},
tick: function () {
this.onTick();
},
respondToCollision: function (other, response) {
this.onCollide(other, response);
// Collisions between "ghostly" objects don't matter, and
// two "heavy" objects will just remain where they are.
if (this.isSolid && other.isSolid &&
!(this.isHeavy && other.isHeavy)) {
if (this.isHeavy) {
// Move the other object out of us
other.data.pos.add(response.overlapV);
} else if (other.isHeavy) {
// Move us out of the other object
this.data.pos.sub(response.overlapV);
} else {
// Move equally out of each other
response.overlapV.scale(0.5);
this.data.pos.sub(response.overlapV);
other.data.pos.add(response.overlapV);
}
}
}
};

function World(canvas, options) {
options = _.defaults(options || {}, {
loopCount: 1 // number of loops to do each time simulation is called. The higher the more accurate the simulation, but slowers.
});
this.canvas = canvas; // A raphael.js canvas
this.response = new SAT.Response(); // Response reused for collisions
this.loopCount = options.loopCount;
this.entities = {};
}
World.prototype = {
addEntity: function(data, options) {
var entity = new Entity(
data,
data instanceof SAT.Circle ? this.canvas.circle() : this.canvas.path(),
options
);
// Make the display item draggable if requested.
if (options.draggable) {
entity.display.drag(moveDrag(entity, this), startDrag(entity), endDrag(entity));
}
entity.updateDisplay();
this.entities[entity.id] = entity;
return entity;
},
removeEntity: function (entity) {
entity.remove();
delete this.entities[entity.id];
},
simulate: function () {
var entities = _.values(this.entities);
var entitiesLen = entities.length;
// Let the entity do something every simulation tick
_.each(entities, function (entity) {
entity.tick();
});
// Handle collisions - loop a configurable number of times to let things "settle"
var loopCount = this.loopCount;
for (var i = 0; i < loopCount; i++) {
// Naively check for collision between all pairs of entities
// E.g if there are 4 entities: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)
for (var aCount = 0; aCount < entitiesLen; aCount++) {
var a = entities[aCount];
for (var bCount = aCount + 1; bCount < entitiesLen; bCount++) {
var b = entities[bCount];
this.response.clear();
var collided;
var aData = a.data;
var bData = b.data;
if (aData instanceof SAT.Circle) {
if (bData instanceof SAT.Circle) {
collided = SAT.testCircleCircle(aData, bData, this.response);
} else {
collided = SAT.testCirclePolygon(aData, bData, this.response);
}
} else {
if (bData instanceof SAT.Circle) {
collided = SAT.testPolygonCircle(aData, bData, this.response);
} else {
collided = SAT.testPolygonPolygon(aData, bData, this.response);
}
}
if (collided) {
a.respondToCollision(b, this.response);
}
}
}
}
// Finally, update the display of each entity now that the simulation step is done.
_.each(entities, function (entity) {
entity.updateDisplay();
});
}
};

(function () {
var canvas = Raphael('example1', 640, 480);
var world = new World(canvas);
var poly = world.addEntity(P(V(160,120), [V(0,0), V(60, 0), V(100, 40), V(60, 80), V(0, 80)]).translate(-50, -40), { solid: true, draggable: true });
var poly2 = world.addEntity(P(V(10,10), [V(0,0), V(30, 0), V(30, 30), V(0, 30)]), { solid: true, draggable: true });
var circle1 = world.addEntity(C(V(50, 200), 30), { solid: true, heavy: true, draggable: true });
function doRotate() {
poly.data.setAngle(poly.data.angle + (Math.PI / 60)); // Assuming 60fps this will take ~2 seconds for a full rotation
world.simulate();
window.requestAnimationFrame(doRotate);
}
window.requestAnimationFrame(doRotate);
}());

(function () {
var canvas = Raphael('example2', 640, 640);
var world = new World(canvas, {
loopCount: 5
});
for (var i = 0; i < 16; i++) {
for (var j = 0; j < 16; j++) {
var displayAttrs = {
fill: 'rgba(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ')'
}
var c = world.addEntity(C(V((40 * i) + 20, (40 * j) + 20), 18), { solid: true, draggable: true, displayAttrs: displayAttrs });
}
}
}());

Draggable-DIV styling based on its position

I don't know why jQuery doesn't animate it to the right. But you can simulate the behavior by animating left by this amount:

$('body').width() - $(this).width() - 8

The number 8 accounts for the 8px border.

The reason the percentage reappears on mouse over is due to this code:

$(this).on("mousemove", function () {
...
$("#border_left_position_percentage").css({
...
"display": "block"
});

Even though it's defined within the dragstart event, it gets attached to the element, so it's always triggered whenever the mouse moves over the element.

In my code, I've moved the mousemove event outside of the dragstart event, and I don't change the display CSS:

$('.right').on('mousemove', function() {
var percentuale = parseInt((($(this).position().left / $(this).parent().width()) * 100), 10);
$("#border_left_position_percentage").html(percentuale + "%");
});

I've also moved the logic/CSS of your mousemove event to the dragstop event.

The dragstart event is now simply:

$('#border_left_position_percentage').css('display','block');
$(this).stop();

This shows the element, which then gets updated while dragging due to the mousemove event. It also stops any animations in progress, so you can grab the box while it's moving.

Fiddle

How to make div draggable with other div on top of it

Add pointer-events: none to the CSS for the border element. It will make it untargetable and all click/drag/touch events will pass through it .

First time trying to create a draggable div in jQuery but it doesn't work

You should include the following references in the project:

  • jquery-ui.css
  • jquery-.js
  • jquery-ui.js

Additionally you have to define the <style> element inside the <head></head> block.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- The following references have been added to the project. -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<!-- The <style> element has been moved inside the <head> block. -->
<style>
#drag {
background-color: rgb(89, 0, 255);
height: 60px;
width: 150px;
}
</style>
</head>
<body>
<div id="drag">
<p>content</p>
</div>

<script>
$(document).ready(() => {
$(function () {
$("#drag").draggable();
});
})
</script>
</body>
</html>


Related Topics



Leave a reply



Submit